Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const bodyParser = require('body-parser');
- const util = require('util');
- const fs = require('fs');
- const dauria = require('dauria');
- const app = express();
- const knex = require('knex')({
- client: 'mysql',
- connection: {
- host: 'localhost',
- port: '3306',
- user: 'root',
- password: 'irena8707',
- database: 'apitest',
- },
- });
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: true }));
- // const print = {
- // posts: [{
- // post_id: '',
- // create_on: '',
- // title: '',
- // content: '',
- // categories: [],
- // cover_image: {
- // file_id: '',
- // path: '',
- // },
- // }],
- // };
- // const pageposts = {
- // post_id: '',
- // create_on: '',
- // title: '',
- // content: '',
- // categories: [],
- // cover_image: '',
- // };
- function getpostlist() {
- return knex('post')
- .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.file_id', 'image.path')
- .join('image', 'post.post_id', '=', 'image.file_id')
- .then((rows) => {
- const print = { posts: [] };
- print.posts = rows.map(post => ({
- post_id: post.post_id,
- create_on: post.create_on,
- title: post.title,
- content: post.content,
- categories: [],
- cover_image: { file_id: post.file_id, path: post.path },
- }));
- return Promise.resolve(print);
- })
- .then(print => knex('categories').select('categories', 'post_id')
- .then((row) => {
- const result = print.posts.map((post) => {
- post.categories = row.filter(postcat => postcat.post_id === post.post_id) // eslint-disable-line
- .map(category => category.categories);
- return post;
- });
- console.log(result);
- return Promise.resolve(result);
- }))
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function getpost(id) {
- return knex('post')
- .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.file_id', 'image.path')
- .join('image', 'image.file_id', '=', 'post.post_id')
- .andWhere('post_id', id)
- .then((rows) => {
- if (rows.length === 0) return Promise.reject(new Error('Not Found'));
- const print = [];
- print.push({
- post_id: rows[0].post_id,
- created_on: rows[0].create_on,
- title: rows[0].title,
- content: rows[0].content,
- categories: [],
- cover_image: {
- file_id: rows[0].file_id,
- path: rows[0].path,
- },
- });
- return knex('categories')
- .select('categories')
- .where('post_id', print[0].post_id)
- .then((row) => {
- print[0].categories = row.map(cat => cat.categories);
- return Promise.resolve(print[0]);
- });
- })
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function getcategories() {
- return knex('categories')
- .select('categories')
- .then((rows) => {
- const print = { categories: [] };
- const reg = rows.map(cat => cat.categories);
- print.categories = reg.filter((element, index, arr) => arr.indexOf(element) === index);
- return Promise.resolve(print);
- })
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function getpagelist() {
- return knex('post')
- .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.uri')
- .join('image', 'post.post_id', '=', 'image.file_id')
- .then((rows) => {
- const print = { posts: [] };
- print.posts = rows.map(post => ({
- post_id: post.post_id,
- create_on: post.create_on,
- title: post.title,
- content: post.content,
- categories: [],
- cover_image: post.uri,
- }));
- return knex('categories').select('categories', 'post_id')
- .then((row) => {
- const result = print.posts.map((post) => {
- post.categories = row.filter(postcat => postcat.post_id === post.post_id) // eslint-disable-line
- .map(cat => cat.categories);
- return post;
- });
- return Promise.resolve(result);
- });
- })
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function getpage(id) {
- return knex('post')
- .select('post.post_id', 'post.title', 'post.content', 'post.create_on', 'image.uri')
- .join('image', 'image.file_id', '=', 'post.post_id')
- .andWhere('post_id', id)
- .then((rows) => {
- if (rows.length === 0) return Promise.reject(new Error('Not Found'));
- const print = [];
- print.push({
- post_id: rows[0].post_id,
- created_on: rows[0].create_on,
- title: rows[0].title,
- content: rows[0].content,
- categories: [],
- cover_image: rows[0].uri,
- });
- return knex('categories')
- .select('categories')
- .where('post_id', print[0].post_id)
- .then((row) => {
- print[0].categories = row.map(cat => cat.categories);
- return Promise.resolve(print[0]);
- });
- })
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function deletepost(id) {
- return knex('post').del()
- .where('post_id', id)
- .then((rows) => {
- if (rows === 0) return Promise.reject(new Error('Not Found'));
- return knex('image').del()
- .where('file_id', id);
- })
- .then(() => knex('categories').del()
- .where('post_id', id))
- .catch((err) => {
- console.error(err);
- throw err;
- });
- }
- function createpost(req) {
- return knex('post').insert({ title: req.body.title, content: req.body.content, create_on: Math.floor(new Date().valueOf() / 1000) })
- .returning('post_id')
- .then((id) => {
- if (req.body.uri) {
- const path = `image${id}.png`;
- const writeFile = util.promisify(fs.writeFile);
- return writeFile(path, dauria.parseDataURI(req.body.uri).buffer).then((err) => {
- if (err) return Promise.reject(err);
- const img = [id, req.body.uri, path];
- return Promise.resolve(img);
- });
- }
- const img = [id, null, null];
- return Promise.resolve(img);
- })
- .then(img => knex('image')
- .insert({ file_id: img[0], uri: img[1], path: img[2] })
- .returning('file_id'))
- .then((id) => {
- let category = [];
- if (req.body.categories) {
- category = req.body.categories.map(cat => ({ post_id: id, categories: cat }));
- }
- return knex('categories')
- .insert(category)
- .then(() => id);
- })
- .then(id => Promise.resolve(getpost(id)));
- }
- function patchpost(id, req) {
- return knex('post').select('title', 'content')
- .where('post_id', id)
- .then((rows) => {
- if (rows.length === 0) return Promise.reject(new Error('Not Found'));
- const title = req.body.title || rows[0].title;
- const content = req.body.content || rows[0].content;
- return knex('post').update({ title, content })
- .where('post_id', id);
- })
- .then(() => knex('categories').select('categories')
- .where('post_id', id))
- .then((row) => {
- if (req.body.categories) {
- const cate = row.map(c => c.categories);
- const catdel = cate.filter(c => !req.body.categories.includes(c));
- const catadd = req.body.categories.filter(c => !cate.includes(c));
- if (catdel[0]) {
- return knex('categories').del().whereIn('categories', catdel).andWhere('post_id', id)
- .then(() => catadd);
- } return Promise.resolve(catadd);
- }
- return Promise.resolve();
- })
- .then((catadd) => {
- if (req.body.categories) {
- if (catadd[0]) {
- const cateadd = catadd.map(cat => ({ post_id: id, categories: cat }));
- return knex('categories').insert(cateadd);
- }
- return Promise.resolve();
- }
- return Promise.resolve();
- })
- .then(() => {
- if (req.body.uri) {
- console.log('image O');
- const path = `image${id}.png`;
- const writeFile = util.promisify(fs.writeFile);
- return writeFile(path, dauria.parseDataURI(req.body.uri).buffer).then((err) => {
- if (err) return Promise.reject(err);
- return knex('image')
- .update({ uri: req.body.uri, path })
- .where('file_id', id);
- });
- }
- return Promise.resolve();
- })
- .then(() => Promise.resolve(getpost(id)))
- .catch(err => Promise.reject(err));
- }
- app.get('/api/post', (req, res) => {
- getpostlist()
- .then((values) => {
- console.log('200');
- return res.status(200).json(values);
- })
- .catch((err) => {
- console.log('500');
- return res.status(500).json(err);
- });
- });
- app.get('/api/post/categories', (req, res) => {
- getcategories()
- .then((values) => {
- res.status(200).json(values);
- });
- });
- app.get('/api/post/:id', (req, res) => {
- getpost(+req.params.id)
- .then((values) => {
- console.log('200');
- return res.status(200).json(values);
- })
- .catch((err) => {
- if (err.message === 'Not Found') {
- console.log('404');
- return res.status(404).json({ code: 404, message: 'Not found' });
- }
- console.log('500');
- return res.status(500).json(err);
- });
- });
- app.get('/api/page/post', (req, res) => {
- getpagelist()
- .then((values) => {
- console.log('200');
- return res.status(200).json(values);
- })
- .catch((err) => {
- console.log('500');
- return res.status(500).json(err);
- });
- });
- app.get('/api/page/post/:id', (req, res) => {
- getpage(req.params.id)
- .then((values) => {
- console.log('200');
- return res.status(200).json(values);
- })
- .catch((err) => {
- if (err.message === 'Not Found') {
- console.log('404');
- return res.status(404).json({ code: 404, message: 'Not found' });
- }
- console.log('500');
- return res.status(500).json(err);
- });
- });
- app.post('/api/post', (req, res) => {
- createpost(req)
- .then((values) => {
- console.log('200');
- return res.status(200).json(values);
- })
- .catch((err) => {
- console.log(err);
- return res.status(500).json(err);
- });
- });
- app.patch('/api/post/:id', (req, res) => {
- patchpost(req.params.id, req)
- .then((values) => {
- console.log('200');
- res.status(200).json(values);
- })
- .catch((err) => {
- if (err.message === 'Not Found') {
- console.log('404');
- res.status(404).json({ code: 404, message: 'Not Found' });
- } else {
- console.log('500');
- res.status(500).json(err);
- }
- });
- });
- app.delete('/api/post/:id', (req, res) => {
- deletepost(req.params.id)
- .then(() => {
- console.log('200');
- res.status(200).send('刪除OK!');
- })
- .catch((err) => {
- if (err.message === 'Not Found') {
- console.log('404');
- return res.status(404).json({ code: 404, message: 'Not found' });
- }
- console.log('500');
- return res.status(500).json(err);
- });
- });
- app.listen(3000, () => {
- console.log('connected localhost:3000');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement