Guest User

Untitled

a guest
Jun 25th, 2017
30
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 uuidV4 = require('uuid/v4');
  9. const mongodb = require('mongodb').MongoClient;
  10.  
  11. const app = new Koa();
  12. const router = Router();
  13.  
  14. let db = null;
  15.  
  16. app.use(bodyParser({
  17.   'formLimit': '50mb',
  18.   'jsonLimit': '50mb',
  19.   'textLimit': '50mb'
  20. }));
  21.  
  22. app.use(async (ctx, next) => {
  23.   if (db == null) {
  24.     db = await mongodb.connect('mongodb://localhost:27017/Library', {
  25.       autoReconnect: true,
  26.       poolSize: 10,
  27.     });
  28.   }
  29.   ctx.db = db;
  30.   await next();
  31. });
  32.  
  33. // 設定根路徑的處理函數
  34. router.get('/', async function(ctx) {
  35.   ctx.body = 'Hello World';
  36. });
  37.  
  38. // login
  39. router.use('/api/login', async function(ctx, next) {
  40.   ctx.set('Access-Control-Allow-Origin', '*');
  41.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  42.   await next();
  43. });
  44.  
  45. router.options('/api/login', async function(ctx) {
  46.   ctx.body = { code: 200, msg: '登入成功' };
  47. });
  48.  
  49. router.post('/api/login', async function(ctx) {
  50.   const username = await ctx.request.body.username;
  51.   const password = await ctx.request.body.password;
  52.  
  53.   var user = {
  54.     id: 1,
  55.     username: 'admin',
  56.     password: '123456',
  57.     avatar: 'https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png',
  58.     name: '张某某'
  59.   };
  60.   user = JSON.parse(JSON.stringify(user));
  61.  
  62.   console.log(`username: ${username}, password: ${password}`);
  63.   ctx.body = { code: 200, msg: '登入成功', user };
  64. });
  65.  
  66.  
  67. // martial classic classification
  68.  
  69. router.use('/api/martial/classic/classifications', async function(ctx, next) {
  70.   ctx.set('Access-Control-Allow-Origin', '*');
  71.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  72.   await next()
  73. });
  74.  
  75. router.options('/api/martial/classic/classifications', async function(ctx) {
  76.   ctx.body = { code: 200, msg: '資料更新成功' };
  77. });
  78.  
  79. router.post('/api/martial/classic/classifications', async function(ctx) {
  80.   const firstTitle = await ctx.request.body.firstTitle;
  81.   const secondTitle = await ctx.request.body.secondTitle;
  82.   const imageGroup = await ctx.request.body.imageGroup;
  83.  
  84.   const collection = ctx.db.collection('Martial');
  85.  
  86.   let ts = new Date().getTime();
  87.  
  88.   try {
  89.     let data = await collection.updateOne(
  90.       {
  91.         pageName: "classic"
  92.       },
  93.       {
  94.         $set: {
  95.           pageName: 'classic',
  96.           'pageData.firstTitle': firstTitle,
  97.           'pageData.secondTitle': secondTitle,
  98.           'pageData.imageGroup': imageGroup,
  99.           'pageData.lastTime': ts
  100.         }
  101.       },
  102.       {
  103.         upsert: true
  104.       }
  105.     );
  106.     console.log('Classifications successfully update');
  107.   } catch (e) {
  108.     console.log(e);
  109.     console.log('Classifications failed to update');
  110.   }
  111.  
  112.   ctx.body = { code: 200, msg: '資料更新成功' };
  113. });
  114.  
  115. router.get('/api/martial/classic/classifications', async function (ctx) {
  116.   const data = await getClassic(ctx.db);
  117.   ctx.body = { code: 200, msg: '資料讀取成功', data: data };
  118. });
  119.  
  120. async function getClassic (db) {
  121.   const collection = db.collection('Martial');
  122.   try {
  123.     let data = await collection.find({ "pageName": "classic" }).toArray();
  124.     console.log('Classifications successfully respond');
  125.     return Promise.resolve(data);
  126.   } catch (err) {
  127.     console.log('Classifications failed to respond');
  128.     return Promise.reject(err);
  129.   }
  130. }
  131.  
  132. // get classification name
  133.  
  134. router.use('/api/classifications/name', async function(ctx, next) {
  135.   ctx.set('Access-Control-Allow-Origin', '*');
  136.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  137.   await next()
  138. });
  139.  
  140. router.get('/api/classifications/name', async function (ctx) {
  141.   let data = [];
  142.   let classicObject = await getClassificationsName( ctx.db, 'classic' );
  143.   let classicResult = await formatClassificationsObject( classicObject );
  144.  
  145.   if ( classicResult != null ) data.push(classicResult);
  146.  
  147.   ctx.body = { code: 200, msg: '資料讀取成功', data: data };
  148. });
  149.  
  150. async function getClassificationsName ( db, pageName ) {
  151.   const collection = db.collection('Martial');
  152.   try {
  153.     let data = await collection.find({ "pageName": pageName }, { "pageData.imageGroup.src": 0 }).toArray();
  154.     console.log('Classifications name successfully respond');
  155.     return Promise.resolve(data);
  156.   } catch (err) {
  157.     console.log('Classifications name failed to respond');
  158.     return Promise.reject(err);
  159.   }
  160. }
  161.  
  162. async function formatClassificationsObject ( object ) {
  163.   let result;
  164.   let classificationsList = [];
  165.  
  166.   try {
  167.     let pageName = object[0].pageName;
  168.  
  169.     object[0].pageData.imageGroup.forEach(function (item) {
  170.       classificationsList.push({
  171.         index: item.index,
  172.         classification: item.firstTitle
  173.       });
  174.     });
  175.  
  176.     result = {
  177.       'pageName': pageName,
  178.       'classifications': classificationsList
  179.     };
  180.  
  181.     return Promise.resolve(result);
  182.   } catch (err) {
  183.     return null;
  184.   }
  185. }
  186.  
  187. // martial classic books
  188.  
  189. router.use('/api/martial/classic/books', async function(ctx, next) {
  190.   ctx.set('Access-Control-Allow-Origin', '*');
  191.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  192.   await next()
  193. });
  194.  
  195. router.options('/api/martial/classic/books', async function(ctx) {
  196.   ctx.body = { code: 200, msg: '書本新增成功' };
  197. });
  198.  
  199. router.post('/api/martial/classic/books', async function(ctx) {
  200.   const pageName = await ctx.request.body.pageName;
  201.   const classificationIndex = await ctx.request.body.classificationIndex;
  202.   const booksList = await ctx.request.body.imageGroup;
  203.  
  204.   const collection = ctx.db.collection('Martial');
  205.  
  206.   try {
  207.     let data = await collection.update(
  208.       {
  209.         pageName: pageName
  210.       },
  211.       {
  212.         $set: {
  213.           [`pageData.imageGroup.${classificationIndex}.booksList`]: booksList
  214.         }
  215.       },
  216.       {
  217.         upsert: true
  218.       }
  219.     );
  220.     console.log('BookList successfully update');
  221.   } catch (e) {
  222.     console.log(e);
  223.     console.log('BookList failed to update');
  224.   }
  225.  
  226.   ctx.body = { code: 200, msg: '文章新增成功' };
  227. });
  228.  
  229. router.use('/api/martial/classic/books', async function(ctx, next) {
  230.   ctx.set('Access-Control-Allow-Origin', '*');
  231.   ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  232.   await next()
  233. });
  234.  
  235. router.get('/api/martial/classic/books', async function (ctx) {
  236.   const classificationIndex = ctx.request.query.classificationIndex;
  237.  
  238.   let booksObject = await getClassificationsBooks( ctx.db, classificationIndex );
  239.   let booksList = await formatClassificationBooksObject( classificationIndex, booksObject );
  240.  
  241.   ctx.body = { code: 200, msg: '資料讀取成功', data: booksList };
  242. });
  243.  
  244. async function getClassificationsBooks ( db, index ) {
  245.   const collection = db.collection('Martial');
  246.   try {
  247.     let data = await collection.aggregate([
  248.       { "$match" : { "pageName" : "classic" } },
  249.       { "$unwind" : "$pageData.imageGroup" },
  250.       { "$match" : { "pageData.imageGroup.index" : parseInt(index) } },
  251.       { "$project" : { "pageData.imageGroup" : 1 } }
  252.     ]).toArray();
  253.  
  254.     console.log('Classifications books successfully respond');
  255.     return Promise.resolve(data);
  256.   } catch (err) {
  257.     console.log('Classifications books failed to respond');
  258.     return Promise.reject(err);
  259.   }
  260. }
  261.  
  262. async function formatClassificationBooksObject ( index, object ) {
  263.  
  264.   try {
  265.  
  266.     let result = {
  267.       'classificationIndex': parseInt(index),
  268.       'booksList': object[0].pageData.imageGroup.booksList
  269.     };
  270.  
  271.     return Promise.resolve(result);
  272.   } catch (err) {
  273.     return null;
  274.   }
  275. }
  276.  
  277. app.use(router.routes());
  278.  
  279. app.listen(3001, function() {
  280.   console.log('Listening on port 3001');
  281. });
Add Comment
Please, Sign In to add comment