Advertisement
Guest User

Untitled

a guest
Jun 17th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Created by max on 2017/6/5.
  3.  */
  4.  
  5. const Koa = require('koa');
  6. const Router = require('koa-router');
  7. const bodyParser = require('koa-bodyparser');
  8. const uuid = require('node-uuid');
  9. const mongodb = require('mongodb');
  10.  
  11. const app = new Koa();
  12. const router = Router();
  13. const mongodbServer = new mongodb.Server('localhost', 27017, { auto_reconnect: true, poolSize: 10 });
  14. const db = new mongodb.Db('Library', mongodbServer);
  15.  
  16. app.use(bodyParser({
  17.   'formLimit': '50mb',
  18.   'jsonLimit': '50mb',
  19.   'textLimit': '50mb'
  20. }));
  21.  
  22. // 設定根路徑的處理函數
  23. router.get('/', async function(ctx) {
  24.   ctx.body = 'Hello World';
  25. });
  26.  
  27.  
  28. // login
  29.  
  30. router.use('/api/login', async function(ctx, next) {
  31.   ctx.set('Access-Control-Allow-Origin', '*');
  32.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  33.   await next()
  34. });
  35.  
  36. router.options('/api/login', async function(ctx) {
  37.   ctx.body = { code: 200, msg: '登入成功' };
  38. });
  39.  
  40. router.post('/api/login', async function(ctx) {
  41.   const username = await ctx.request.body.username;
  42.   const password = await ctx.request.body.password;
  43.  
  44.   var user = {
  45.     id: 1,
  46.     username: 'admin',
  47.     password: '123456',
  48.     avatar: 'https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png',
  49.     name: '张某某'
  50.   };
  51.   user = JSON.parse(JSON.stringify(user));
  52.  
  53.   console.log(`username: ${username}, password: ${password}`);
  54.   ctx.body = { code: 200, msg: '登入成功', user };
  55. });
  56.  
  57.  
  58. // martial classic classification
  59.  
  60. router.use('/api/martial/classic/classifications', async function(ctx, next) {
  61.   ctx.set('Access-Control-Allow-Origin', '*');
  62.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  63.   await next()
  64. });
  65.  
  66. router.options('/api/martial/classic/classifications', async function(ctx) {
  67.   ctx.body = { code: 200, msg: '文章新增成功' };
  68. });
  69.  
  70. router.post('/api/martial/classic/classifications', async function(ctx) {
  71.   const title = await ctx.request.body.title;
  72.   const secondTitle = await ctx.request.body.secondTitle;
  73.   const imageGroup = await ctx.request.body.imageGroup;
  74.  
  75.   db.open(function() {
  76.     db.collection('Martial', function(err, collection) {
  77.  
  78.       var uuidBinary = new Buffer(uuid.v1({}, []));
  79.       var id = mongodb.Binary(uuidBinary, mongodb.Binary.SUBTYPE_UUID);
  80.  
  81.       /* Generate Timestamp and convert for mongodb */
  82.       var ts = new Date().getTime();
  83.       var i = ts % 1000;
  84.       var t = new mongodb.Timestamp(i, Math.floor(ts * 0.001));
  85.  
  86.       /* Insert a data with uuid */
  87.       collection.update(
  88.         {
  89.           pageName: "classic"
  90.         },
  91.         {
  92.           pageName: 'classic',
  93.           pageData: {
  94.             title: title,
  95.             secondTitle: secondTitle,
  96.             imageGroup: imageGroup,
  97.             lastTime: t
  98.           }
  99.         },
  100.         {
  101.           upsert: true
  102.         },
  103.         function(err, data) {
  104.           if (data) {
  105.             console.log('Successfully Update');
  106.             db.close();
  107.           } else {
  108.             console.log('Failed to Update');
  109.           }
  110.         }
  111.       );
  112.  
  113.     });
  114.   });
  115.  
  116.   ctx.body = { code: 200, msg: '文章新增成功' };
  117. });
  118.  
  119. router.get('/api/martial/classic/classifications', async function(ctx) {
  120.   const data = await getClassic();
  121.   ctx.body = { code: 200, msg: '資料讀取成功', data: data };
  122. });
  123.  
  124. async function getClassic () {
  125.   return new Promise(function(resolve, reject) {
  126.     db.open(function() {
  127.       db.collection('Martial', function(err, collection) {
  128.  
  129.         collection.find(
  130.           {
  131.             "pageName": "classic"
  132.           },
  133.           function(err, data) {
  134.             if (data) {
  135.               const dataArr = data.toArray();
  136.               console.log('Successfully Update');
  137.               db.close();
  138.               resolve(dataArr);
  139.             } else {
  140.               console.log('Failed to Update');
  141.             }
  142.           }
  143.         );
  144.  
  145.       });
  146.     });
  147.   });
  148. }
  149.  
  150. router.get('/api/classifications/name', async function(ctx) {
  151.   let data = [];
  152.   let classicObject = await getClassificationsName( 'classic' );
  153.   let classicResult = await formatClassificationsObject( classicObject );
  154.  
  155.   data.push(classicResult);
  156.  
  157.   ctx.body = { code: 200, msg: '資料讀取成功', data: data };
  158. });
  159.  
  160. async function getClassificationsName ( pageName ) {
  161.   return new Promise(function(resolve, reject) {
  162.     db.open(function() {
  163.       db.collection('Martial', function(err, collection) {
  164.  
  165.         collection.find(
  166.           {
  167.             "pageName": pageName
  168.           },
  169.           {
  170.             "pageData.imageGroup.src": 0
  171.           },
  172.           function(err, data) {
  173.             if (data) {
  174.               const dataArr = data.toArray();
  175.               db.close();
  176.               resolve(dataArr);
  177.               console.log('Successfully Update');
  178.             } else {
  179.               console.log('Failed to Update');
  180.             }
  181.           }
  182.         );
  183.  
  184.       });
  185.     });
  186.   });
  187. }
  188.  
  189. async function formatClassificationsObject ( object ) {
  190.   return new Promise(function (resolve, reject) {
  191.  
  192.     let result;
  193.     let classificationsList = [];
  194.     let pageName = object[0].pageName;
  195.  
  196.     object[0].pageData.imageGroup.forEach( function( item ) {
  197.       classificationsList.push( item['first_title'] );
  198.     });
  199.  
  200.     result = {
  201.       'pageName': pageName,
  202.       'classifications': classificationsList
  203.     };
  204.  
  205.     resolve( result );
  206.  
  207.   });
  208. }
  209.  
  210.  
  211. app.use(router.routes());
  212.  
  213. app.listen(3001, function() {
  214.   console.log('Listening on port 3001');
  215. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement