Huh Jin-Ho

add server code

server_code @ bca4d754
Subproject commit bca4d754b2f01d09d2c9eec4522a79ae6cb7537c
No preview for this file type
node_modules
./dff
\ No newline at end of file
version: 0.0
os: linux
files:
- source: /
destination: /opt/food_test
hooks:
ApplicationStop:
- location: deployment_scripts/stop.sh
timeout: 180
AfterInstall:
- location: deployment_scripts/deploy.sh
timeout: 180
ApplicationStart:
- location: deployment_scripts/start.sh
timeout: 180
#!/bin/bash
cd /opt/food_test
sudo npm install
sudo node /opt/food_test/src/create_database.js
sudo node /opt/food_test/src/insert_db.js
#!/usr/bin/env bash
#sudo pm2 stop node-app
# actually start the server
sudo pm2 start /opt/food_test/src/bin/www -i 0 --name "node-app"
#!/usr/bin/env bash
sudo pm2 stop node-app
\ No newline at end of file
This diff is collapsed. Click to expand it.
{
"name": "food-waste",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./src/bin/www"
},
"dependencies": {
"acron": "^1.0.5",
"aws-sdk": "^2.587.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"morgan": "~1.9.1"
}
}
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./router.js');
// var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(200));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('food-waste:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
var AWS = require('aws-sdk');
AWS.config.update({
region: "ap-northeast-2",
})
var dynamodb = new AWS.DynamoDB();
var pi_data =
{
TableName: 'pi_data',
KeySchema: [
{ // Required
AttributeName: 'ras_id',
KeyType: 'HASH',
},
{ // Optional
AttributeName: 'save_date',
KeyType: 'RANGE',
}
],
AttributeDefinitions: [
{
AttributeName: 'ras_id',
AttributeType: 'S', // (S | N | B) for string, number, binary
},
{
AttributeName: 'save_date',
AttributeType: 'S', // (S | N | B) for string, number, binary
}
],
ProvisionedThroughput: { // required provisioned throughput for the table
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
}
};
// var user_data =
// {
// TableName: 'user_data',
// KeySchema: [
// { // Required
// AttributeName: 'user_id',
// KeyType: 'HASH',
// }
// ],
// AttributeDefinitions: [
// {
// AttributeName: 'user_id',
// AttributeType: 'S', // (S | N | B) for string, number, binary
// }
// ],
// ProvisionedThroughput: { // required provisioned throughput for the table
// ReadCapacityUnits: 1,
// WriteCapacityUnits: 1,
// }
// };
dynamodb.createTable(pi_data, function(err, data) {
if (err) {
console.log(err); // an error occurred
} else {
console.log(data); // successful response
}
});
dynamodb.createTable(user_data, function(err, data) {
if (err) {
console.log(err); // an error occurred
} else {
console.log(data); // successful response
}
});
var AWS = require("aws-sdk");
var fs = require('fs');
AWS.config.update({
region: "ap-northeast-2"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var pi_table = "pi_data";
var user_table = "user_data";
var dynamodb = new AWS.DynamoDB();
function get_last_weight(ras_id,cb){
params = {
TableName : pi_table,
ExpressionAttributeValues: {
":ras_id": {
S: ras_id
}
},
KeyConditionExpression : "ras_id = :ras_id",
"ScanIndexForward":false,
"Limit" : 1,
}
console.log(ras_id)
dynamodb.query(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log(data.Items[0])
var last_weight = data.Items[0].weight.N
console.log("Last Weight : ",last_weight)
cb(last_weight)
}
});
}
module.exports = {
save_pi_data: function(pi_data,cb){
console.log(pi_data)
get_last_weight(pi_data.ras_id,function(last_weight){
console.log(last_weight)
var diff_weight = pi_data.weight - last_weight;
if(diff_weight < 0) diff_weight = 0;
var date = new Date(pi_data.date)
date = date.getTime().toString()
var params = {
TableName : pi_table,
Item : {
"ras_id" : pi_data.ras_id,
"save_date" : pi_data,
"weight" : Number(pi_data.weight),
"diff" : diff_weight
}
}
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
cb(false)
} else {
console.log("Added item:", params);
cb(true)
}
});
})
},
save_app_data: function(app_data,cb){
// var app_data = JSON.parse(app_data);
var params = {
TableName : user_table,
Item : {
"ras_id" : app_data.ras_id,
"user_id" : app_data.user_id
}
}
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
cb(false)
} else {
console.log("Added item:", params);
cb(true)
}
});
},
get_user_data: function(ras_id,cb){
// var params = {
// TableName : user_table,
// Key : {
// "user_id" : user_id
// }
// }
// console.log(user_id)
// docClient.get(params, function(err, data) {
// if (err) {
// console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
// } else {
// console.log("GetItem succeeded:", data);
// console.log(data.Item)
// if(data.Item){
params = {
TableName : pi_table,
ExpressionAttributeValues: {
":ras_id": { S: ras_id }
},
KeyConditionExpression : "ras_id = :ras_id"
}
dynamodb.query(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
JSON.stringify(data, null, 2)
// console.log(data.Items)
cb(data.Items)
}
});
// }
// else{
// cb("No User")
// }
// }
// });
},
get_diff_data: function(user_info,cb){
console.log(user_info)
params = {
TableName : pi_table,
ExpressionAttributeValues: {
":ras_id": { S: user_info.ras_id},
":save_date" : {S : user_info.date}
},
KeyConditionExpression : "ras_id = :ras_id and save_date > :save_date",
}
dynamodb.query(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
JSON.stringify(data, null, 2)
console.log(data.Items)
cb(data.Items)
}
});
}
}
\ No newline at end of file
var AWS = require('aws-sdk');
AWS.config.update({
region: "ap-northeast-2"
})
var docClient = new AWS.DynamoDB.DocumentClient();
function add_data(params){
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", params);
}
});
}
async function save_random_data(epoch,start,end){
var start_date = start;
var start_weight = 0;
for(var i =0; i<epoch; i++){
console.log(start_date)
var date = await start_date.getTime() + Math.random() * (end.getTime() - start_date.getTime());
start_date = new Date(date)
if(start_weight == 2000)
start_weight = 0
var weight = await Math.floor(Math.random() * (2000-start_weight))+start_weight+1;
var diff = weight - start_weight
if(start_weight == 0) diff = 0
var params = {
TableName : "pi_data",
Item : {
"ras_id" : "pi1",
"save_date" : date.toString(),
"weight" : weight,
"diff" : diff
}
}
await add_data(params);
start_weight = await weight
}
}
save_random_data(10, new Date("2019-12-10"), new Date())
\ No newline at end of file
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
var express = require('express');
var router = express.Router();
var dynamo_access = require('./dynamodb.js')
// router.post('/app/save_data',function(req,res,next){
// var body = req.body;
// dynamo_access.save_app_data(body,function(response){
// console.log(response)
// if(response == true) res.status(200).json("Success")
// else res.status(500).json("Fail")
// });
// })
router.get('/app/get_data/:id',function(req,res,next){
dynamo_access.get_user_data(req.params.id,function(response){
console.log(response)
res.status(200).json(response)
})
})
router.post('/app/get_diff_data',function(req,res,next){
var body = req.body;
console.log(body);
dynamo_access.get_diff_data(body,function(response){
console.log(response)
res.status(200).json(response)
})
})
router.post('/pi/save_data',function(req,res,next){
var body = req.body;
console.log(body);
dynamo_access.save_pi_data(body,function(response){
console.log(response)
if(response == true) res.status(200).json("Success")
else res.status(500).json("Fail")
});
})
module.exports = router;
\ No newline at end of file
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}
extends layout
block content
h1= title
p Welcome to #{title}
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content