Guest User

Untitled

a guest
Jun 7th, 2017
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const koa = require('koa');
  2. const koaRouter = require('koa-router');
  3. const koaBodyParser = require('koa-bodyparser');
  4. const serve = require('koa-static');
  5. const mount = require('koa-mount');
  6. const Ajv = require('ajv');
  7. const Promise = require('bluebird');
  8. const fs = require('fs');
  9. const path = require('path');
  10. const ajv = new Ajv();
  11. const app = new koa();
  12. const router = new koaRouter();
  13.  
  14. Promise.promisifyAll(fs);
  15. app.use(koaBodyParser());
  16. app.use(async(ctx, next) => {
  17.   ctx.set('Content-Type', 'application/json');
  18.   await next();
  19. });
  20. app.use(async(ctx, next) => {
  21.   try { await next(); }
  22.   catch(err){
  23.     ctx.status = err.status || 500;
  24.     ctx.body = {error: err.message};
  25.     ctx.app.emit('error', err, ctx);
  26.   }
  27. })
  28. app.use(mount('/static', serve(path.join(__dirname, 'static'))));
  29.  
  30. const userSchema = {
  31.   properties: {
  32.     uuid: { type: 'integer'},
  33.     name: {type: 'string'},
  34.     profession: { type: 'string'},
  35.     password: {type: 'string'}
  36.   }
  37. }
  38. const validateUser = ajv.compile(userSchema);
  39.  
  40. let userlist = []
  41.  
  42. const saveDb = async function(){
  43.   await fs.writeFileAsync('user.json', JSON.stringify(userlist));
  44. }
  45.  
  46. let actions = {
  47.   list: async (ctx) => {
  48.     ctx.body = JSON.stringify(userlist);
  49.   },
  50.   get: async (ctx) => {
  51.     let findUserList = userlist.filter(user => user.uuid === parseInt(ctx.params.uuid));
  52.     if (findUserList.length > 0) ctx.body = JSON.stringify(findUserList[0]);
  53.     else ctx.throw(404, 'User not found');
  54.   },
  55.   add: async (ctx) => {
  56.     if(!validateUser(ctx.request.body)) ctx.throw(400, 'Incorrect data');
  57.     const newUser = {
  58.       uuid: userlist.length+1,
  59.       name: ctx.request.body.name,
  60.       password: ctx.request.body.password,
  61.       profession: ctx.request.body.profession
  62.     }
  63.     userlist.push(newUser);
  64.     await saveDb();
  65.     ctx.status = 201;
  66.     ctx.body = newUser
  67.   },
  68.   update: async(ctx) => {
  69.     if(!validateUser(ctx.request.body)) ctx.throw(400, 'Incorrect data');
  70.     let userFound = userlist.find(user => user.uuid === parseInt(ctx.params.uuid));
  71.     if (!userFound) ctx.throw(404, 'User not found');
  72.     Object.assign(userFound, ctx.request.body);
  73.     await saveDb();
  74.     ctx.status = 200
  75.     ctx.body = userFound;
  76.   },
  77.   delete: async(ctx) => {
  78.     userlist = userlist.filter(user => user.uuid !== parseInt(ctx.params.uuid));
  79.     await saveDb();
  80.     ctx.status = 200;
  81.     ctx.body = {message: 'Delete successed.'}
  82.   },
  83.   index: async(ctx) => {
  84.     ctx.status = 200;
  85.     ctx.set('Content-Type', 'text/html');
  86.     ctx.body = fs.createReadStream(path.join(__dirname, 'index.html'));
  87.   }
  88. }
  89.  
  90. router.get('/', actions.index)
  91.       .get('/api/user', actions.list)
  92.       .get('/api/user/:uuid', actions.get)
  93.       .post('/api/user', actions.add)
  94.       .put('/api/user/:uuid', actions.update)
  95.       .delete('/api/user/:uuid', actions.delete);
  96.      
  97. app.use(router.routes());
  98. app.use(router.allowedMethods());
  99.  
  100. app.listen(3000, () => {
  101.   console.info("Server started.");
  102. });
Add Comment
Please, Sign In to add comment