Advertisement
irenaLin

Untitled

Oct 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const util = require('util');
  4. const fs = require('fs');
  5. const dauria = require('dauria');
  6.  
  7. const app = express();
  8. const knex = require('knex')({
  9.   client: 'mysql',
  10.   connection: {
  11.     host: 'localhost',
  12.     port: '3306',
  13.     user: 'root',
  14.     password: 'irena8707',
  15.     database: 'apitest',
  16.   },
  17. });
  18.  
  19. app.use(bodyParser.json());
  20. app.use(bodyParser.urlencoded({ extended: true }));
  21.  
  22. // const print = {
  23. //   posts: [{
  24. //     post_id: '',
  25. //     create_on: '',
  26. //     title: '',
  27. //     content: '',
  28. //     categories: [],
  29. //     cover_image: {
  30. //       file_id: '',
  31. //       path: '',
  32. //     },
  33. //   }],
  34. // };
  35.  
  36. // const pageposts = {
  37. //   post_id: '',
  38. //   create_on: '',
  39. //   title: '',
  40. //   content: '',
  41. //   categories: [],
  42. //   cover_image: '',
  43. // };
  44.  
  45. function getpostlist() {
  46.   return knex('post')
  47.     .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.file_id', 'image.path')
  48.     .join('image', 'post.post_id', '=', 'image.file_id')
  49.     .then((rows) => {
  50.       const print = { posts: [] };
  51.       print.posts = rows.map(post => ({
  52.         post_id: post.post_id,
  53.         create_on: post.create_on,
  54.         title: post.title,
  55.         content: post.content,
  56.         categories: [],
  57.         cover_image: { file_id: post.file_id, path: post.path },
  58.       }));
  59.       return Promise.resolve(print);
  60.     })
  61.     .then(print => knex('categories').select('categories', 'post_id')
  62.       .then((row) => {
  63.         const result = print.posts.map((post) => {
  64.           post.categories = row.filter(postcat => postcat.post_id === post.post_id) // eslint-disable-line
  65.             .map(category => category.categories);
  66.           return post;
  67.         });
  68.         console.log(result);
  69.         return Promise.resolve(result);
  70.       }))
  71.     .catch((err) => {
  72.       console.error(err);
  73.       throw err;
  74.     });
  75. }
  76.  
  77. function getpost(id) {
  78.   return knex('post')
  79.     .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.file_id', 'image.path')
  80.     .join('image', 'image.file_id', '=', 'post.post_id')
  81.     .andWhere('post_id', id)
  82.     .then((rows) => {
  83.       if (rows.length === 0) return Promise.reject(new Error('Not Found'));
  84.       const print = [];
  85.       print.push({
  86.         post_id: rows[0].post_id,
  87.         created_on: rows[0].create_on,
  88.         title: rows[0].title,
  89.         content: rows[0].content,
  90.         categories: [],
  91.         cover_image: {
  92.           file_id: rows[0].file_id,
  93.           path: rows[0].path,
  94.         },
  95.       });
  96.       return knex('categories')
  97.         .select('categories')
  98.         .where('post_id', print[0].post_id)
  99.         .then((row) => {
  100.           print[0].categories = row.map(cat => cat.categories);
  101.           return Promise.resolve(print[0]);
  102.         });
  103.     })
  104.     .catch((err) => {
  105.       console.error(err);
  106.       throw err;
  107.     });
  108. }
  109.  
  110. function getcategories() {
  111.   return knex('categories')
  112.     .select('categories')
  113.     .then((rows) => {
  114.       const print = { categories: [] };
  115.       const reg = rows.map(cat => cat.categories);
  116.       print.categories = reg.filter((element, index, arr) => arr.indexOf(element) === index);
  117.       return Promise.resolve(print);
  118.     })
  119.     .catch((err) => {
  120.       console.error(err);
  121.       throw err;
  122.     });
  123. }
  124.  
  125. function getpagelist() {
  126.   return knex('post')
  127.     .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.uri')
  128.     .join('image', 'post.post_id', '=', 'image.file_id')
  129.     .then((rows) => {
  130.       const print = { posts: [] };
  131.       print.posts = rows.map(post => ({
  132.         post_id: post.post_id,
  133.         create_on: post.create_on,
  134.         title: post.title,
  135.         content: post.content,
  136.         categories: [],
  137.         cover_image: post.uri,
  138.       }));
  139.       return knex('categories').select('categories', 'post_id')
  140.         .then((row) => {
  141.           const result = print.posts.map((post) => {
  142.             post.categories = row.filter(postcat => postcat.post_id === post.post_id) // eslint-disable-line
  143.               .map(cat => cat.categories);
  144.             return post;
  145.           });
  146.           return Promise.resolve(result);
  147.         });
  148.     })
  149.     .catch((err) => {
  150.       console.error(err);
  151.       throw err;
  152.     });
  153. }
  154.  
  155. function getpage(id) {
  156.   return knex('post')
  157.     .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.uri')
  158.     .join('image', 'image.file_id', '=', 'post.post_id')
  159.     .andWhere('post_id', id)
  160.     .then((rows) => {
  161.       if (rows.length === 0) return Promise.reject(new Error('Not Found'));
  162.       const print = [];
  163.       print.push({
  164.         post_id: rows[0].post_id,
  165.         created_on: rows[0].create_on,
  166.         title: rows[0].title,
  167.         content: rows[0].content,
  168.         categories: [],
  169.         cover_image: rows[0].uri,
  170.       });
  171.       return knex('categories')
  172.         .select('categories')
  173.         .where('post_id', print[0].post_id)
  174.         .then((row) => {
  175.           print[0].categories = row.map(cat => cat.categories);
  176.           return Promise.resolve(print[0]);
  177.         });
  178.     })
  179.     .catch((err) => {
  180.       console.error(err);
  181.       throw err;
  182.     });
  183. }
  184.  
  185. function deletepost(id) {
  186.   return knex('post').del()
  187.     .where('post_id', id)
  188.     .then((rows) => {
  189.       if (rows === 0) return Promise.reject(new Error('Not Found'));
  190.  
  191.       return knex('image').del()
  192.         .where('file_id', id);
  193.     })
  194.     .then(() => knex('categories').del()
  195.       .where('post_id', id))
  196.     .catch((err) => {
  197.       console.error(err);
  198.       throw err;
  199.     });
  200. }
  201.  
  202. function createpost(req) {
  203.   return knex('post').insert({ title: req.body.title, content: req.body.content, create_on: Math.floor(new Date().valueOf() / 1000) })
  204.     .returning('post_id')
  205.     .then((id) => {
  206.       if (req.body.uri) {
  207.         const path = `image${id}.png`;
  208.         const writeFile = util.promisify(fs.writeFile);
  209.         return writeFile(path, dauria.parseDataURI(req.body.uri).buffer).then((err) => {
  210.           if (err) return Promise.reject(err);
  211.           const img = [id, req.body.uri, path];
  212.           return Promise.resolve(img);
  213.         });
  214.       }
  215.       const img = [id, null, null];
  216.       return Promise.resolve(img);
  217.     })
  218.     .then(img => knex('image')
  219.       .insert({ file_id: img[0], uri: img[1], path: img[2] })
  220.       .returning('file_id'))
  221.     .then((id) => {
  222.       let category = [];
  223.       if (req.body.categories) {
  224.         category = req.body.categories.map(cat => ({ post_id: id, categories: cat }));
  225.       }
  226.       return knex('categories')
  227.         .insert(category)
  228.         .then(() => id);
  229.     })
  230.     .then(id => Promise.resolve(getpost(id)));
  231. }
  232.  
  233. function patchpost(id, req) {
  234.   return knex('post').select('title', 'content')
  235.     .where('post_id', id)
  236.     .then((rows) => {
  237.       if (rows.length === 0) return Promise.reject(new Error('Not Found'));
  238.  
  239.       const title = req.body.title || rows[0].title;
  240.       const content = req.body.content || rows[0].content;
  241.       return knex('post').update({ title, content })
  242.         .where('post_id', id);
  243.     })
  244.     .then(() => knex('categories').select('categories')
  245.       .where('post_id', id))
  246.     .then((row) => {
  247.       if (req.body.categories) {
  248.         const cate = row.map(c => c.categories);
  249.         const catdel = cate.filter(c => !req.body.categories.includes(c));
  250.         const catadd = req.body.categories.filter(c => !cate.includes(c));
  251.         if (catdel[0]) {
  252.           return knex('categories').del().whereIn('categories', catdel).andWhere('post_id', id)
  253.             .then(() => catadd);
  254.         } return Promise.resolve(catadd);
  255.       }
  256.       return Promise.resolve();
  257.     })
  258.     .then((catadd) => {
  259.       if (req.body.categories) {
  260.         if (catadd[0]) {
  261.           const cateadd = catadd.map(cat => ({ post_id: id, categories: cat }));
  262.           return knex('categories').insert(cateadd);
  263.         }
  264.         return Promise.resolve();
  265.       }
  266.  
  267.       return Promise.resolve();
  268.     })
  269.     .then(() => {
  270.       if (req.body.uri) {
  271.         console.log('image O');
  272.         const path = `image${id}.png`;
  273.         const writeFile = util.promisify(fs.writeFile);
  274.         return writeFile(path, dauria.parseDataURI(req.body.uri).buffer).then((err) => {
  275.           if (err) return Promise.reject(err);
  276.           return knex('image')
  277.             .update({ uri: req.body.uri, path })
  278.             .where('file_id', id);
  279.         });
  280.       }
  281.       return Promise.resolve();
  282.     })
  283.     .then(() => Promise.resolve(getpost(id)))
  284.     .catch(err => Promise.reject(err));
  285. }
  286.  
  287.  
  288. app.get('/api/post', (req, res) => {
  289.   getpostlist()
  290.     .then((values) => {
  291.       console.log('200');
  292.       return res.status(200).json(values);
  293.     })
  294.     .catch((err) => {
  295.       console.log('500');
  296.       return res.status(500).json(err);
  297.     });
  298. });
  299. app.get('/api/post/categories', (req, res) => {
  300.   getcategories()
  301.     .then((values) => {
  302.       res.status(200).json(values);
  303.     });
  304. });
  305. app.get('/api/post/:id', (req, res) => {
  306.   getpost(+req.params.id)
  307.     .then((values) => {
  308.       console.log('200');
  309.       return res.status(200).json(values);
  310.     })
  311.     .catch((err) => {
  312.       if (err.message === 'Not Found') {
  313.         console.log('404');
  314.         return res.status(404).json({ code: 404, message: 'Not found' });
  315.       }
  316.       console.log('500');
  317.       return res.status(500).json(err);
  318.     });
  319. });
  320. app.get('/api/page/post', (req, res) => {
  321.   getpagelist()
  322.     .then((values) => {
  323.       console.log('200');
  324.       return res.status(200).json(values);
  325.     })
  326.     .catch((err) => {
  327.       console.log('500');
  328.       return res.status(500).json(err);
  329.     });
  330. });
  331. app.get('/api/page/post/:id', (req, res) => {
  332.   getpage(req.params.id)
  333.     .then((values) => {
  334.       console.log('200');
  335.       return res.status(200).json(values);
  336.     })
  337.     .catch((err) => {
  338.       if (err.message === 'Not Found') {
  339.         console.log('404');
  340.         return res.status(404).json({ code: 404, message: 'Not found' });
  341.       }
  342.       console.log('500');
  343.       return res.status(500).json(err);
  344.     });
  345. });
  346. app.post('/api/post', (req, res) => {
  347.   createpost(req)
  348.     .then((values) => {
  349.       console.log('200');
  350.       return res.status(200).json(values);
  351.     })
  352.     .catch((err) => {
  353.       console.log(err);
  354.       return res.status(500).json(err);
  355.     });
  356. });
  357. app.patch('/api/post/:id', (req, res) => {
  358.   patchpost(req.params.id, req)
  359.     .then((values) => {
  360.       console.log('200');
  361.       res.status(200).json(values);
  362.     })
  363.     .catch((err) => {
  364.       if (err.message === 'Not Found') {
  365.         console.log('404');
  366.         res.status(404).json({ code: 404, message: 'Not Found' });
  367.       } else {
  368.         console.log('500');
  369.         res.status(500).json(err);
  370.       }
  371.     });
  372. });
  373. app.delete('/api/post/:id', (req, res) => {
  374.   deletepost(req.params.id)
  375.     .then(() => {
  376.       console.log('200');
  377.       res.status(200).send('刪除OK!');
  378.     })
  379.     .catch((err) => {
  380.       if (err.message === 'Not Found') {
  381.         console.log('404');
  382.         return res.status(404).json({ code: 404, message: 'Not found' });
  383.       }
  384.       console.log('500');
  385.       return res.status(500).json(err);
  386.     });
  387. });
  388.  
  389.  
  390. app.listen(3000, () => {
  391.   console.log('connected localhost:3000');
  392. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement