Advertisement
Guest User

Untitled

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