From 8f6f391cfe12fb5916a7d62413cd5121dadee873 Mon Sep 17 00:00:00 2001 From: shaoh4 Date: Sun, 3 Jan 2021 23:08:14 +0800 Subject: [PATCH] Frontend code separation --- server/.babelrc | 14 - server/.eslintrc | 50 ---- server/api.test.js | 364 -------------------------- server/index.js | 5 - server/jest.config.js | 3 - server/package.json | 43 --- server/pm2.json | 18 -- server/src/api/api.book.js | 112 -------- server/src/api/api.borrow.js | 149 ----------- server/src/api/api.category.js | 62 ----- server/src/api/api.index.js | 11 - server/src/api/api.user.js | 28 -- server/src/config.js | 20 -- server/src/main.js | 139 ---------- server/src/model/model.book.js | 32 --- server/src/model/model.borrow.js | 32 --- server/src/model/model.category.js | 23 -- server/src/model/model.js | 6 - server/src/model/model.user.js | 27 -- server/src/service/BaseService.js | 238 ----------------- server/src/service/BookService.js | 114 -------- server/src/service/BorrowService.js | 133 ---------- server/src/service/CategoryService.js | 10 - server/src/service/UserService.js | 105 -------- 24 files changed, 1738 deletions(-) delete mode 100644 server/.babelrc delete mode 100644 server/.eslintrc delete mode 100644 server/api.test.js delete mode 100644 server/index.js delete mode 100644 server/jest.config.js delete mode 100644 server/package.json delete mode 100644 server/pm2.json delete mode 100644 server/src/api/api.book.js delete mode 100644 server/src/api/api.borrow.js delete mode 100644 server/src/api/api.category.js delete mode 100644 server/src/api/api.index.js delete mode 100644 server/src/api/api.user.js delete mode 100644 server/src/config.js delete mode 100644 server/src/main.js delete mode 100644 server/src/model/model.book.js delete mode 100644 server/src/model/model.borrow.js delete mode 100644 server/src/model/model.category.js delete mode 100644 server/src/model/model.js delete mode 100644 server/src/model/model.user.js delete mode 100644 server/src/service/BaseService.js delete mode 100644 server/src/service/BookService.js delete mode 100644 server/src/service/BorrowService.js delete mode 100644 server/src/service/CategoryService.js delete mode 100644 server/src/service/UserService.js diff --git a/server/.babelrc b/server/.babelrc deleted file mode 100644 index 88fbb7f..0000000 --- a/server/.babelrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "presets": [ - [ - "@babel/preset-env", - { - "targets": { - "node": "current" - } - } - ] - ], - "plugins": [["transform-class-properties", {"spec": true}]] - -} diff --git a/server/.eslintrc b/server/.eslintrc deleted file mode 100644 index ef47cb1..0000000 --- a/server/.eslintrc +++ /dev/null @@ -1,50 +0,0 @@ -{ - "root": true, - "env": { - "node": true, - "es6": true - }, - "parser": "babel-eslint", - "plugins": ["react"], - "parserOptions": { - "sourceType": "module", - "ecmaVersion": 6 - }, - "rules": { - "max-len": [1, 99, 2], - "semi": 0, - "curly": [2, "multi-line"], - "comma-dangle": [2, "always-multiline"], - "eol-last": [2, "always"], - "eqeqeq": [2, "allow-null"], - "no-shadow": 1, - "quotes": [ - 2, - "single", - { - "allowTemplateLiterals": true, - "avoidEscape": true - } - ], - // dog fooding - "import/no-extraneous-dependencies": 0, - "import/unambiguous": "off" - }, - - "settings": { - "import/resolver": { - "node": { - "paths": ["src"] - } - } - }, - - "overrides": [ - { - "files": "scripts/**", - "rules": { - "no-console": "off" - } - } - ] -} diff --git a/server/api.test.js b/server/api.test.js deleted file mode 100644 index 68d4440..0000000 --- a/server/api.test.js +++ /dev/null @@ -1,364 +0,0 @@ -require('@babel/core'); -require('@babel/register'); -require('@babel/polyfill'); - -import supertest from 'supertest'; -import app from './index'; - -const request = supertest(app); - -jest.useFakeTimers(); - -describe('--', () => { - jest.useFakeTimers(); - beforeAll((done) => { - done(); - }); - - afterAll((done) => { - done(); - }); - let userInfo; - describe('api/user/', () => { - it('signin- successs', async (none) => { - const response = await request.post('/api/user/signin').send({email: 'aaa@qq.com', password: 'aaa'}); - userInfo = JSON.parse(response.text).data; - - expect(response.status).toBe(200); - none(); - }); - - it('signin- email is not empty', async () => { - const response = await request.post('/api/user/signin').send({email: '', password: 'aaaa'}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('email is not empty'); - }); - it('signin- password is not empty', async () => { - const response = await request.post('/api/user/signin').send({email: 'aaa@qq.com', password: ''}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('password is not empty'); - }); - it('signin- email Incorrect format', async () => { - const response = await request.post('/api/user/signin').send({email: 'aaaqq.com', password: 'aasq'}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('email Incorrect format'); - }); - it('signin- invalid username or password', async () => { - const response = await request.post('/api/user/signin').send({email: 'aaa@qq.com', password: 'aaaa'}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('invalid username or password'); - }); - - const data1 = {username: 'jest_build_name', email: `tmp.${parseInt(Math.random() * 1000)}@tmp.com`, password: '111', confirmPwd: '111', address: 'address', zip_code: '1234'}; - it('signup- username is not empty', async () => { - const data = JSON.parse(JSON.stringify(data1)); - delete data.username; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('username is not empty'); - }); - it('signup- email is not empty', async () => { - const data = JSON.parse(JSON.stringify(data1)); - delete data.email; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('email is not empty'); - }); - it('signup- email Incorrect format', async () => { - const data = JSON.parse(JSON.stringify(data1)); - data.email = '1111.com'; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('email Incorrect format'); - }); - it('signup- password is not empty', async () => { - const data = JSON.parse(JSON.stringify(data1)); - delete data.password; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('password is not empty'); - }); - it('signup- incorrect password input twice', async () => { - const data = JSON.parse(JSON.stringify(data1)); - data.confirmPwd = 1231; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('incorrect password input twice'); - }); - it('signup- address', async () => { - const data = JSON.parse(JSON.stringify(data1)); - delete data.address; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('address is not empty'); - }); - it('signup- email exists', async () => { - const data = JSON.parse(JSON.stringify(data1)); - data.email = 'aaa@qq.com'; - const response = await request.post('/api/user/signup').send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('email exists'); - }); - }); - - describe('/api/category', () => { - it('get category list', async () => { - const response = await request.get('/api/category'); - expect(response.status).toBe(200); - }); - it('get all category list', async () => { - const response = await request.get('/api/category/all'); - expect(response.status).toBe(200); - }); - - it('category name is not empty', async () => { - const response = await request.post('/api/category').send({name: ''}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('category name is not empty'); - }); - - it('category name is exists -- add', async () => { - const allInfo = await request.get('/api/category'); - const row0 = JSON.parse(allInfo.text).data[0]; - const response = await request.post('/api/category').send({name: row0.name}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('category name is exists'); - }); - - it('category name is exists -- update', async () => { - const allInfo = await request.get('/api/category'); - const row0 = JSON.parse(allInfo.text).data[0]; - const row1 = JSON.parse(allInfo.text).data[1]; - const response = await request.put('/api/category/' + row0.id).send({name: row1.name}); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('category name is exists'); - }); - }); - - describe('/api/book', () => { - let bookList; - let book_id; - it('/search', async () => { - const response = await request.get('/api/book/search').query({keyword: '12'}); - bookList = JSON.parse(response.text).data; - book_id = bookList.list[0].id; - expect(response.status).toBe(200); - }); - it('/search error', async () => { - const response = await request.get('/api/book/search').query({keyword: 'aa', page: -1, size: 10}); - expect(response.status).toBe(400); - }); - it('/my Unauthorized 401', async () => { - const response = await request.get('/api/book/my'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/my list', async () => { - const response = await request.get('/api/book/my').set('token', userInfo.token); - expect(response.status).toBe(200); - }); - it('/detail ', async () => { - const id = bookList.list[0].id; - const response = await request.get('/api/book/' + id).set('token', userInfo.token); - expect(response.status).toBe(200); - }); - const bookInfo = { - category: 'category', - book_name: 'book_name', - price: 11, - author: 'jest_author', - ISBN: 'jest-isbn', - state: 1, - describe: 'jest-describe', - }; - it('/post add book - category is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.category; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book category is not empty'); - }); - it('/post add book - price is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.price; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book price is not empty'); - }); - it('/post add book - price incorrect', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - data.price = -1; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book price incorrect'); - }); - it('/post add book - author is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.author; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book author is not empty'); - }); - it('/post add book - ISBN is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.ISBN; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book ISBN is not empty'); - }); - it('/post add book - describe is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.describe; - const response = await request.post('/api/book/').set('token', userInfo.token).send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book describe is not empty'); - }); - - it('/delete delete book ', async () => { - const response = await request.delete('/api/book/5fdb80b40d44a700c88f4449').set('token', userInfo.token); - expect(response.status).toBe(200); - }); - - it('/put update book - category is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.category; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book category is not empty'); - }); - it('/put update book - name is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.book_name; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book name is not empty'); - }); - it('/put update book - price is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.price; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book price is not empty'); - }); - it('/put update book - price incorrect', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - data.price = -1; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book price incorrect'); - }); - it('/put update book - author is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.author; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book author is not empty'); - }); - it('/put update book - ISBN is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.ISBN; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book ISBN is not empty'); - }); - it('/put update book - describe is not empty', async () => { - const data = JSON.parse(JSON.stringify(bookInfo)); - delete data.describe; - const response = await request - .put('/api/book/' + book_id) - .set('token', userInfo.token) - .send(data); - expect(response.status).toBe(400); - expect(JSON.parse(response.text).msg).toBe('book describe is not empty'); - }); - it('/put update book - 401', async (done) => { - const data = JSON.parse(JSON.stringify(bookInfo)); - const response = await request.put('/api/book/' + book_id).send(data); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - done(); - }); - it('/delete update book - 401', async (done) => { - const data = JSON.parse(JSON.stringify(bookInfo)); - const response = await request.delete('/api/book/' + book_id).send(data); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - done(); - }); - it('/post add book - 401', async (done) => { - const data = JSON.parse(JSON.stringify(bookInfo)); - const response = await request.post('/api/book/').send(data); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - done(); - }); - }); - - describe('/api/borrow', () => { - it('/post borrow 401', async () => { - const response = await request.post('/api/borrow'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - - it('/post borrow 400', async () => { - const response = await request.post('/api/borrow'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - - it('/:id Unauthorized 401', async () => { - const response = await request.put('/api/borrow/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/request/msg/:id request msg Unauthorized 401', async () => { - const response = await request.put('/api/borrow/request/msg/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/reply/msg/:id reply msg Unauthorized 401', async () => { - const response = await request.put('/api/borrow/reply/msg/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/refuse/:id refuse Unauthorized 401', async () => { - const response = await request.put('/api/borrow/refuse/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/confirm/:id confirm Unauthorized 401', async () => { - const response = await request.put('/api/borrow/confirm/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/delete Unauthorized 401', async () => { - const response = await request.delete('/api/borrow/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - it('/get detail Unauthorized 401', async () => { - const response = await request.get('/api/borrow/5fdc210371f94122600e3601'); - expect(response.status).toBe(401); - expect(JSON.parse(response.text).data).toBe('Unauthorized'); - }); - }); -}); diff --git a/server/index.js b/server/index.js deleted file mode 100644 index 80ac181..0000000 --- a/server/index.js +++ /dev/null @@ -1,5 +0,0 @@ -require('@babel/core'); -require('@babel/register'); -require('@babel/polyfill'); -const app = require('./src/main'); -module.exports = app; diff --git a/server/jest.config.js b/server/jest.config.js deleted file mode 100644 index f2837b4..0000000 --- a/server/jest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - testEnvironment: 'node' -}; \ No newline at end of file diff --git a/server/package.json b/server/package.json deleted file mode 100644 index 5062f3f..0000000 --- a/server/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "server", - "version": "1.0.0", - "main": "index.js", - "license": "MIT", - "scripts": { - "dev": "better-npm-run start-dev", - "test1": "jest --runInBand --testTimeout=5000 --coverage --detectOpenHandles", - "test": "jest --runInBand --testTimeout=5000 --coverage" - }, - "betterScripts": { - "start-dev": { - "command": "nodemon index.js --ignore public/", - "env": { - "PORT": 4900, - "NODE_ENV": "development" - } - } - }, - "keywords": [], - "author": "", - "dependencies": { - "@babel/core": "^7.10.4", - "@babel/polyfill": "^7.10.4", - "@babel/preset-env": "^7.10.4", - "@babel/register": "^7.10.4", - "babel-eslint": "^10.1.0", - "babel-plugin-transform-class-properties": "^6.24.1", - "bcrypt": "^5.0.0", - "bcryptjs": "^2.4.3", - "better-npm-run": "^0.1.1", - "crypto": "^1.0.1", - "eslint": "^6.7.2", - "express": "^4.17.1", - "express-session": "^1.17.1", - "jest": "^26.6.3", - "jsonwebtoken": "^8.5.1", - "mongoose": "^5.10.10", - "multer": "^1.4.2", - "nodemon": "^2.0.6", - "supertest": "^6.0.1" - } -} diff --git a/server/pm2.json b/server/pm2.json deleted file mode 100644 index 89391bc..0000000 --- a/server/pm2.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "apps": [{ - "name": "node-borrow", - "script": "index.js", - "exec_mode": "cluster", - "instances": 1, - "max_memory_restart": "1G", - "autorestart": true, - "node_args": [], - "args": [], - "out_file": "/mnt/log/node-borrow/out.log", - "error_file": "/mnt/log/node-borrow/err.log", - "env": { - "PORT": 3280, - "NODE_ENV": "production" - } - }] -} diff --git a/server/src/api/api.book.js b/server/src/api/api.book.js deleted file mode 100644 index 8ca67cd..0000000 --- a/server/src/api/api.book.js +++ /dev/null @@ -1,112 +0,0 @@ -import express from 'express'; -import BookService from '../service/BookService'; -import UserService from '../service/UserService'; -const multer = require('multer'); - -const upload = multer({ dest: 'uploads/' }); - -const router = express.Router(); - -router - // get category list - .get('/search', async (request, response) => { - try { - const { keyword, page = 1, size = 20 } = request.query; - const opt = { state: true }; - if (keyword) { - opt.$or = []; - opt.$or.push({ book_name: { $regex: keyword, $options: '$i' } }); - opt.$or.push({ author: { $regex: keyword, $options: '$i' } }); - opt.$or.push({ ISBN: { $regex: keyword, $options: '$i' } }); - opt.$or.push({ category: { $regex: keyword, $options: '$i' } }); - } - - const limit = Number(size); - const skip = (Number(page) - 1) * limit; - const list = await BookService.find(opt, { create_time: 0, update_time: 0 }, { limit, skip }); - const total = await BookService.count(opt); - const totalPage = Math.ceil(total / Number(size)) - response.json(BookService.success({ list, total, page: Number(page), size: Number(size), totalPage })); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - .get('/my', async (request, response) => { - try { - const { userInfo } = request; - if (!userInfo) { - response.status(401).json({ code: 401, data: 'Unauthorized' }); - return; - } - const list = await BookService.find({ user_id: userInfo.id }); - response.json(BookService.success(list)); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - .get('/:id', async (request, response) => { - try { - const { id } = request.params; - const detail = await BookService.findById(id); - response.json(BookService.success(detail)); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // add book - .post('/', upload.single('file'), async (request, response) => { - try { - const [isExpire, userInfo] = await UserService.CheckToken(request.token); - if (isExpire) { - response.status(401).json({ code: 401, data: 'Unauthorized' }); - return; - } - - const data = request.body; - data.file = request.file; - data.userInfo = userInfo; - - const info = await BookService.AddBook(data); - response.json(info); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // delete book by id - .delete('/:id', async (request, response) => { - try { - if (!request.token) { - response.status(401).json({ code: 401, data: 'Unauthorized' }); - return; - } - const { id } = request.params; - if (!id) { - BookService.failure('id is not empty'); - } - await BookService.findByIdAndDelete(id); - response.json(BookService.success('delete success')); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // update book name - .put('/:id', upload.single('file'), async (request, response) => { - try { - if (!request.token) { - response.status(401).json({ code: 401, data: 'Unauthorized' }); - return; - } - - const { id } = request.params; - const data = request.body; - data.file = request.file; - data.userInfo = request.userInfo; - - const info = await BookService.UpdateBook(id, request.body); - response.json(info); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }); - -export default router; diff --git a/server/src/api/api.borrow.js b/server/src/api/api.borrow.js deleted file mode 100644 index 6e8f0ea..0000000 --- a/server/src/api/api.borrow.js +++ /dev/null @@ -1,149 +0,0 @@ -import express from 'express'; -import BorrowService from '../service/BorrowService'; - -const router = express.Router(); - -router - // authority judgment - .use(async (request, response, next) => { - try { - const userInfo = request.userInfo; - if (!userInfo) { - response.status('401').json({code: 401, data: 'Unauthorized'}); - return; - } - await next(); - } catch (ex) { - response.status('400').json({code: 400, data: ex.msg || ex.message || ex}); - } - }) - // add borrow record - .post('/', async (request, response) => { - try { - const userInfo = request.userInfo; - const data = request.body; - data.userInfo = userInfo; - - const info = await BorrowService.AddBorrow(data); - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // delete by id - .delete('/:id', async (request, response) => { - try { - if (!request.token) { - response.status(401).json({code: 401, data: 'Unauthorized'}); - return; - } - const {id: request_user_id} = request.userInfo; - const {id} = request.params; - if (!id) { - BorrowService.failure('id is not empty'); - } - const isExists = await BorrowService.count({_id: id, request_user_id}); - console.log('isExists:', isExists, id, request_user_id); - if (isExists == 0) { - BorrowService.failure(`it's not your record. I don't have permission`); - } - await BorrowService.findByIdAndDelete(id); - response.json(BorrowService.success('delete success')); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // get borrow list - .get('/my', async (request, response) => { - try { - if (!request.token) { - response.status(401).json({code: 401, data: 'Unauthorized'}); - return; - } - - const list = await BorrowService.find({request_user_id: request.userInfo.id}); - response.json(BorrowService.success(list)); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // get requester list - .get('/request', async (request, response) => { - try { - if (!request.token) { - response.status(401).json({code: 401, data: 'Unauthorized'}); - return; - } - - const list = await BorrowService.find({book_user_id: request.userInfo.id}); - response.json(BorrowService.success(list)); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // get borrow detail - .get('/:id', async (request, response) => { - try { - const info = await BorrowService.findById(request.params.id); - response.json(BorrowService.success(info)); - } catch (ex) { - response.status('400').json({code: 400, data: ex.msg || ex.message || ex}); - } - }) - // add message - .put('/request/msg/:id', async (request, response) => { - try { - const {id} = request.params; - const {content: request_msg} = request.body; - const info = await BorrowService.AddRequestMsg(id, request_msg); - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // replay requester message - .put('/reply/msg/:id', async (request, response) => { - try { - const {id} = request.params; - const {content: reply_msg} = request.body; - const info = await BorrowService.AddReplyMsg(id, reply_msg); - // $push - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // refuse requester - .put('/refuse/:id', async (request, response) => { - try { - const {id} = request.params; - const {content} = request.body; - const info = await BorrowService.Refuse(id, content); - // $push - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - // confirm requester - .put('/confirm/:id', async (request, response) => { - try { - const {id} = request.params; - const {content} = request.body; - const info = await BorrowService.Confirm(id, content); - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }) - .put('/return/:id', async (request, response) => { - try { - const {id} = request.params; - const info = await BorrowService.Return(id); - response.json(info); - } catch (ex) { - response.status(400).json({code: 400, msg: ex.msg || ex.message || ex}); - } - }); - -export default router; diff --git a/server/src/api/api.category.js b/server/src/api/api.category.js deleted file mode 100644 index 859b4d3..0000000 --- a/server/src/api/api.category.js +++ /dev/null @@ -1,62 +0,0 @@ -import express from 'express'; -import CategoryService from '../service/CategoryService'; - -const router = express.Router(); - -router - // get category list - .get('/', async (request, response) => { - try { - const info = await CategoryService.find({ state: 1 }, { create_time: 0, update_time: 0 }); - response.json(CategoryService.success(info)); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - .get('/all', async (request, response) => { - try { - const info = await CategoryService.find({}, { create_time: 0, update_time: 0 }); - response.json(CategoryService.success(info)); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // add category - .post('/', async (request, response) => { - try { - const { name } = request.body; - if (!name) { - CategoryService.failure('category name is not empty'); - } - const row = await CategoryService.findOne({ name }); - if (row) { - CategoryService.failure('category name is exists'); - } - - await CategoryService.create({ name }); - - response.json(CategoryService.success('add success')); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // update category name - .put('/:id', async (request, response) => { - try { - const { id } = request.params; - const { name, state } = request.body; - const opt = { name, _id: { $ne: id } }; - console.log(opt); - - const item = await CategoryService.findOne(opt); - if (item) { - CategoryService.failure('category name is exists'); - } - await CategoryService.findByIdAndUpdate(id, request.body); - response.json(CategoryService.success('update success')); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }); - -export default router; diff --git a/server/src/api/api.index.js b/server/src/api/api.index.js deleted file mode 100644 index 11e70b7..0000000 --- a/server/src/api/api.index.js +++ /dev/null @@ -1,11 +0,0 @@ -import user from './api.user'; -import category from './api.category'; -import book from './api.book'; -import borrow from './api.borrow'; - -export default (app) => { - app.use('/api/user', user);// user signup and signin - app.use('/api/category', category); // create,update category - app.use('/api/book', book); // add ,delete,update book - app.use('/api/borrow', borrow); // get ,add ,delete borrow -}; diff --git a/server/src/api/api.user.js b/server/src/api/api.user.js deleted file mode 100644 index 24d8694..0000000 --- a/server/src/api/api.user.js +++ /dev/null @@ -1,28 +0,0 @@ -import express from 'express'; -import UserService from '../service/UserService'; - -const router = express.Router(); - -router - // signup - .post('/signup', async (request, response) => { - try { - const body = request.body; - const info = await UserService.SignUp(body); - response.json(info); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }) - // sign in - .post('/signin', async (request, response) => { - try { - const body = request.body; - const info = await UserService.UserSingin(body); - response.json(info); - } catch (ex) { - response.status(400).json({ code: 400, msg: ex.msg || ex.message || ex }); - } - }); - -export default router; diff --git a/server/src/config.js b/server/src/config.js deleted file mode 100644 index 6f639ae..0000000 --- a/server/src/config.js +++ /dev/null @@ -1,20 +0,0 @@ -const config = { - development: { - dbConn: 'mongodb://BorrowBook:BorrowBook_BorrowBook@175.24.101.94/BorrowBook', - jwtKey: 'shaoh4_304CEM@coventry.ac.uk', - }, - production: { - dbConn: 'mongodb://BorrowBook:BorrowBook_BorrowBook@175.24.101.94/BorrowBook', - jwtKey: 'shaoh4_304CEM@coventry.ac.uk', - }, - test: { - dbConn: 'mongodb://BorrowBook:BorrowBook_BorrowBook@175.24.101.94/BorrowBook', - jwtKey: 'shaoh4_304CEM@coventry.ac.uk', - } -} - -export default config[process.env.NODE_ENV || 'development']; - -// module.exports = { - -// }[process.env.NODE_ENV || 'development'] \ No newline at end of file diff --git a/server/src/main.js b/server/src/main.js deleted file mode 100644 index a63a1cb..0000000 --- a/server/src/main.js +++ /dev/null @@ -1,139 +0,0 @@ -import http from 'http'; -import path from 'path'; -import mongoose from 'mongoose'; -import express from 'express'; -import session from 'express-session'; -import bodyParser from 'body-parser'; -import fs from 'fs'; -import cfg from './config'; - -import router from './api/api.index'; -import UserService from './service/UserService'; - -const port = process.env.PORT || 4900; -// console log -function printLog() { - try { - const _curDate = new Date(); - const info = `${_curDate.getFullYear()}-${ - _curDate.getMonth() + 1 - }-${_curDate.getDate()} ${_curDate.getHours()}:${_curDate.getMinutes()}:${_curDate.getSeconds()}.${_curDate.getMilliseconds()}`; - console.log(`${info}-->`, ...arguments); - } catch (ex) { - console.log(ex); - } -} - -const app = express(); -const staticPath = path.join(__dirname, '../public'); -// create static resource directory -if (!fs.existsSync(staticPath)) { - fs.mkdirSync(staticPath, {recursive: true}); -} -app.use(express.static(staticPath)); - -app.use(express.json()); -app.use(express.urlencoded({extended: false})); -app.use(bodyParser.json()); -app.use( - session({ - cookie: {secure: true, maxAge: 60 * 60 * 24, httpOnly: true, path: '/'}, - secret: 'nodex-express@!@#$1234', - resave: false, - saveUninitialized: false, - }), -); - -// console print request method and url path; -app.use(async function (req, res, next) { - const {headers, method, url} = req; - - res.header('Access-Control-Allow-Origin', '*'); - res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization,token, Accept, X-Requested-With'); - res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); - if (req.method == 'OPTIONS') { - res.send(200); - } else { - req.token = headers.token; - const [isExpire, userInfo] = await UserService.CheckToken(req.token); - if (!isExpire) { - req.userInfo = userInfo; - } else { - req.token = ''; - } - printLog('method:', method.toLowerCase(), url); - await next(); - } -}); - -// init router -router(app); - -app.use('/', (req, res, next) => { - res.statusCode = 404; - res.send({code: 404, msg: 'method not found'}); - next(); -}); - -app.use(function (err, req, res, next) { - if (res.locals) { - res.locals.message = err.message; - res.locals.error = err; - } - console.log('----------------------error----------', err.status); - console.log(err); - res.status(err.status || 500).send(JSON.stringify({code: err.status || 500, msg: err.message})); -}); - -app.set('port', port); - -const server = http.createServer(app); -server.listen(port); - -server.on('error', (error) => { - console.log('---------enter error info------------'); - if (error.syscall !== 'listen') { - throw error; - } - - var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; - switch (error.code) { - case 'EACCES': - console.error(bind + ' requires elevated privileges'); - process.exit(1); - break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); - process.exit(1); - break; - default: - throw error; - } -}); - -// create mongodb connection -const MongoDbConn = () => { - mongoose.connect(cfg.dbConn, {useUnifiedTopology: true, useNewUrlParser: true}, function (err) { - if (err) throw err; - console.log('Connected to mongodb success'); - }); -}; - -// listening -server.on('listening', () => { - printLog(`http://127.0.0.1:${port}/api`); - try { - MongoDbConn(); - } catch (ex) { - // - } -}); - -process.on('unhandledRejection', (err, b, next) => { - console.log('error', err.message); - if (next) { - next(); - } -}); - -export default app; diff --git a/server/src/model/model.book.js b/server/src/model/model.book.js deleted file mode 100644 index dffd9a8..0000000 --- a/server/src/model/model.book.js +++ /dev/null @@ -1,32 +0,0 @@ -import mongoose from 'mongoose'; -const {Schema} = mongoose; - -export default mongoose.model( - 'book', - new Schema( - { - user_id: {type: String, default: ''}, - username: {type: String, default: ''}, - category: {type: String, default: ''}, - book_name: {type: String, default: ''}, - price: {type: Number, default: ''}, - author: {type: String, default: ''}, - image: {type: String, default: ''}, - ISBN: {type: String, default: ''}, - state: {type: Boolean, default: false}, - is_borrow: {type: Boolean, default: false}, - describe: {type: String, default: ''}, - }, - { - timestamps: {createdAt: 'create_time', updatedAt: 'update_time'}, - toJSON: { - virtuals: true, - transform(doc, ret) { - delete ret.__v; - delete ret._id; - return ret; - }, - }, - }, - ), -); diff --git a/server/src/model/model.borrow.js b/server/src/model/model.borrow.js deleted file mode 100644 index b22dff1..0000000 --- a/server/src/model/model.borrow.js +++ /dev/null @@ -1,32 +0,0 @@ -import mongoose from 'mongoose'; -const {Schema} = mongoose; - -export default mongoose.model( - 'borrow', - new Schema( - { - book_id: {type: String, default: ''}, - book_user_id: {type: String, default: ''}, - book_username: {type: String, default: ''}, - book_address: {type: String, default: ''}, - book_name: {type: String, default: ''}, - book_price: {type: Number, default: 0}, - request_user_id: {type: String, default: ''}, - request_username: {type: String, default: ''}, - request_address: {type: String, default: ''}, - message: {type: Array, default: []}, - state: {type: Number, default: 1, commit: '1:normal,2:confirm,3:refuse,4: return'}, - }, - { - timestamps: {createdAt: 'create_time', updatedAt: 'update_time'}, - toJSON: { - virtuals: true, - transform(doc, ret) { - delete ret.__v; - delete ret._id; - return ret; - }, - }, - }, - ), -); diff --git a/server/src/model/model.category.js b/server/src/model/model.category.js deleted file mode 100644 index 2707599..0000000 --- a/server/src/model/model.category.js +++ /dev/null @@ -1,23 +0,0 @@ -import mongoose from 'mongoose'; -const { Schema } = mongoose; - -export default mongoose.model( - 'category', - new Schema( - { - name: { type: String, default: '' }, - state: { type: Boolean, default: true }, - }, - { - timestamps: { createdAt: 'create_time', updatedAt: 'update_time' }, - toJSON: { - virtuals: true, - transform(doc, ret) { - delete ret.__v; - delete ret._id; - return ret; - }, - }, - }, - ), -); diff --git a/server/src/model/model.js b/server/src/model/model.js deleted file mode 100644 index 325ab28..0000000 --- a/server/src/model/model.js +++ /dev/null @@ -1,6 +0,0 @@ -import ModelUser from './model.user'; -import ModelBook from './model.book'; -import ModelCategory from './model.category'; -import ModelBorrow from './model.borrow'; - -export {ModelUser, ModelBook, ModelCategory, ModelBorrow}; diff --git a/server/src/model/model.user.js b/server/src/model/model.user.js deleted file mode 100644 index 6626267..0000000 --- a/server/src/model/model.user.js +++ /dev/null @@ -1,27 +0,0 @@ -import mongoose from 'mongoose'; -const {Schema} = mongoose; - -export default mongoose.model( - 'user', - new Schema( - { - username: {type: String, default: ''}, - password: {type: String, default: ''}, - address: {type: String, default: ''}, - email: {type: String, default: ''}, - role: {type: Number, default: 1, commit: '1:general,2:admin'}, - zip_code: {type: String, default: ''}, - }, - { - timestamps: {createdAt: 'create_time', updatedAt: 'update_time'}, - toJSON: { - virtuals: true, - transform(doc, ret) { - delete ret.__v; - delete ret._id; - return ret; - }, - }, - }, - ), -); diff --git a/server/src/service/BaseService.js b/server/src/service/BaseService.js deleted file mode 100644 index 150789f..0000000 --- a/server/src/service/BaseService.js +++ /dev/null @@ -1,238 +0,0 @@ -/** - * Operation database base class - * - * @class BaseService - */ -export default class BaseService { - constructor(modal) { - this.modal = modal; - } - - /** - * console output log - * - * @memberof MongoDbHelper - */ - log() { - try { - const _curDate = new Date(); - const info = `${_curDate.getFullYear()}-${ - _curDate.getMonth() + 1 - }-${_curDate.getDay()} ${_curDate.getHours()}:${_curDate.getMinutes()}:${_curDate.getSeconds()}.${_curDate.getMilliseconds()}`; - console.log(`${info}-->`, ...arguments); - } catch (ex) { - console.log(ex); - console.log(args); - } - } - - /** - * find record by id - * - * @param {*} id - * @returns - * @memberof BaseService - */ - async findById(id) { - const info = await this.modal.findById(id); - return info ? JSON.parse(JSON.stringify(info)) : null; - } - - /** - * return record list - * - * @static - * @param {any} condition {field1:'conditionValue',type:4 ...} - * @param {any} [fields={}] - * @param {any} [options={}] {sort:{fiel4:-1,..}, limit:10, skip:0, ...} - * @returns - * @memberof BaseService - */ - async find(condition = {}, fields = {}, options = {}) { - try { - const list = await this.modal.find(condition, fields, options); - return list ? JSON.parse(JSON.stringify(list)) : []; - } catch (ex) { - this.log(ex); - this.failure(ex.message) - } - } - - /** - * save document to db - * - * @param {any} fields - * @returns - * @memberof BaseService - */ - async save(fields) { - try { - const result = await this.modal.create(fields); - return result ? result.toJSON() : null; - } catch (ex) { - this.log(ex); - return Promise.reject({msg: `save doucment error:${ex.message}`}); - } - } - - /** - * create - * - * @param {*} docs - * @return {*} - */ - async create(docs) { - return this.save(docs); - } - - /** - * find first document by condition - * - * @param {any} condition {field1:'conditionValue',type:4 ...} - * @param {any} [fields={}] - * @param {any} [options={}] {sort:{fiel4:-1,..},...} - * @returns - * @memberof BaseService - */ - async findOne(condition, fields = {}, options = {}) { - try { - const result = await this.modal.findOne(condition, fields, options); - return result ? result.toJSON() : null; - } catch (ex) { - this.log(ex); - return null; - } - } - - /** - * modify document by id - * - * @param {any} id PK - * @param {any} fields {field1:'a',field2:'b'...} - * @returns - * @memberof BaseService - */ - async findByIdAndUpdate(id, fields) { - try { - const condition = {_id: id}; - await this.modal.updateOne(condition, {$set: fields}); - const result = await this.modal.findById(id); - return result ? result.toJSON() : null; - } catch (ex) { - this.log(ex); - return Promise.reject({msg: `[${this.TableName}]update error :${ex.message}`}); - } - } - - /** - * update document fields by condition - * - * @param {*} condition - * @param {*} fields - * @returns - * @memberof BaseService - */ - async updateByCondition(condition, fields) { - try { - await this.modal.updateOne(condition, fields); - const result = await this.modal.findOne(condition); - return result ? result.toJSON() : null; - } catch (ex) { - this.log(ex); - return Promise.reject({msg: `[${this.TableName}]update error :${ex.message}`}); - } - } - - /** - * delete document by id - * - * @param {*} id - * @returns - * @memberof BaseService - */ - async findByIdAndDelete(id) { - return this.modal.findByIdAndDelete(id); - } - - /** - * get document count by condition - * - * @param {*} condition - * @returns - * @memberof BaseService - */ - async count(condition) { - return this.modal.countDocuments(condition); - } - - /** - * batch update doucment - * - * @param {*} condition - * @param {*} updateField - * @returns - * @memberof BaseService - */ - async updateMany(condition, updateField) { - try { - await this.modal.updateMany({...condition}, {$set: {...updateField}}); - } catch (ex) { - this.log(ex); - return Promise.reject({msg: `[${this.TableName}]update error :${ex.message}`}); - } - } - - /** - * - * - * @param {*} aggregations = [ {$group : {} } , {$project:{} }, {$match: {}} ] - * @example - * this.aggregate( - * [ - * { - * $group: { - * _id: { worker_id: '$worker_id' }, - * totalPrice: { $sum: '$price' } - * } - * }, - * { - * $project: { worker_id: '$_id.worker_id', total: '$totalPrice' } - * }, - * { - * $match: { worker_id: '5f6eb0eb5025214504cd2377' } - * } - * ]) - * - * @return {*} - */ - async aggregate(aggregations) { - try { - const result = await this.modal.aggregate(aggregations); - return result && result.length > 0 ? JSON.parse(JSON.stringify(result[0])) : null; - } catch (ex) { - this.log(ex); - return Promise.reject({msg: `[${this.TableName}]update error :${ex.message}`}); - } - } - - /** - * error process - * - * @param {*} msg - * @memberof BaseService - */ - failure(msg) { - throw Error(msg); - } - - /** - * return success content - * - * @param {*} msg - * @returns - * @memberof BaseService - */ - success(msg) { - return {code: 200, data: msg}; - } -} diff --git a/server/src/service/BookService.js b/server/src/service/BookService.js deleted file mode 100644 index 7d19dab..0000000 --- a/server/src/service/BookService.js +++ /dev/null @@ -1,114 +0,0 @@ -import path from 'path'; -import fs from 'fs'; -import { ModelBook } from '../model/model'; -import BaseService from './BaseService'; - -class BookService extends BaseService { - constructor() { - super(ModelBook); - } - - /** - * add book infomation - * - * @param {*} data - * @returns - * @memberof BookService - */ - async AddBook(data) { - const { file, userInfo, category, book_name, price, author, ISBN, state, describe } = data; - const { id: user_id, username } = userInfo || {}; - data.image = this.saveFile(file); - data.user_id = user_id; - data.username = username; - if (!category) { - this.failure('book category is not empty'); - } - if (!book_name) { - this.failure('book name is not empty'); - } - if (!price) { - this.failure('book price is not empty'); - } - if (price < 0) { - this.failure('book price incorrect'); - } - if (!author) { - this.failure('book author is not empty'); - } - if (!ISBN) { - this.failure('book ISBN is not empty'); - } - if (!describe) { - this.failure('book describe is not empty'); - } - - await this.create(data); - return this.success('add success'); - } - - /** - * update book infomation - * - * @param {*} id - * @param {*} data - * @returns - * @memberof BookService - */ - async UpdateBook(id, data) { - - const { file, userInfo, category, image, book_name, price, author, ISBN, state, describe } = data; - data.image = this.saveFile(file) || image; - if (!category) { - this.failure('book category is not empty'); - } - if (!book_name) { - this.failure('book name is not empty'); - } - if (!price) { - this.failure('book price is not empty'); - } - if (price < 0) { - this.failure('book price incorrect'); - } - if (!author) { - this.failure('book author is not empty'); - } - if (!ISBN) { - this.failure('book ISBN is not empty'); - } - if (!describe) { - this.failure('book describe is not empty'); - } - await this.findByIdAndUpdate(id, { category, book_name, image: data.image, price, author, ISBN, state, describe }); - const newResult = await this.findById(id); - return this.success(newResult); - } - - - /** - * save file - * - * @param {*} file - * @returns - * @memberof BookService - */ - saveFile(file) { - if (!file) { - return ''; - } - - const { originalname, path: filePath } = file; - const rootDir = path.join(__dirname, '../../', 'public', 'images'); - if (!fs.existsSync(rootDir)) { - fs.mkdirSync(rootDir, { recursive: true }); - } - const fileName = `${new Date().getTime()}_${originalname}`; - const targetName = path.join(rootDir, fileName); - fs.renameSync(filePath, targetName); - - return `/images/${fileName}`; - } -} - -export default new BookService(); diff --git a/server/src/service/BorrowService.js b/server/src/service/BorrowService.js deleted file mode 100644 index b904e69..0000000 --- a/server/src/service/BorrowService.js +++ /dev/null @@ -1,133 +0,0 @@ -import {ModelBorrow} from '../model/model'; -import BaseService from './BaseService'; -import UserService from './UserService'; -import BookService from './BookService'; - -class BorrowService extends BaseService { - constructor() { - super(ModelBorrow); - } - - /** - * add borrow - * - * @param {*} data - * @returns - * @memberof BorrowService - */ - async AddBorrow(data) { - const {userInfo, id: book_id, book_name, user_id: book_user_id, username: book_username, price: book_price, message} = data; - const {id: request_user_id, username: request_username, address: request_address} = userInfo || {}; - // judge is exists - const isExists = await this.findOne({book_id, request_user_id, state: 1}); - if (isExists) { - this.failure('you have added'); - } - if (book_user_id == request_user_id) { - this.failure('wrong, the current book is your own'); - } - - const bookUser = await UserService.findById(book_user_id); - - await this.create({ - book_id, - book_user_id, - book_username, - book_name, - book_price, - book_address: bookUser.address, - request_user_id, - request_address, - request_username, - message: [{request_msg: message, create_time: new Date(), reply_msg: ''}], - }); - return this.success('add success'); - } - - /** - * requester msg - * - * @param {*} id - * @param {*} request_msg - * @returns - * @memberof BorrowService - */ - async AddRequestMsg(id, request_msg) { - if (!request_msg) { - this.failure('message content is not empty'); - } - console.log('id:', id, 'content:', request_msg); - await this.updateByCondition({_id: id}, {$push: {message: {request_msg, create_time: new Date(), reply_msg: ''}}}); - return this.success('add success'); - } - - /** - * reply msg - * - * @param {*} id - * @param {*} reply_msg - * @returns - * @memberof BorrowService - */ - async AddReplyMsg(id, reply_msg) { - if (!reply_msg) { - this.failure('reply message is not empty'); - } - await this.updateByCondition({_id: id}, {$push: {message: {request_msg: '', reply_msg, create_time: new Date()}}}); - return this.success('add success'); - } - - /** - * refuse requester - * - * @param {*} id - * @param {*} content - * @returns - * @memberof BorrowService - */ - async Refuse(id, content) { - if (!content) { - this.failure('please fill in the reason for rejection'); - } - await this.updateByCondition({_id: id}, {state: 3, $push: {message: {request_msg: '', reply_msg: content, create_time: new Date()}}}); - return this.success('operator success'); - } - - /** - * confirm requester - * - * @param {*} id - * @param {*} content - * @returns - * @memberof BorrowService - */ - async Confirm(id, content) { - const info = await this.findById(id); - - const item = await BookService.findById(info.book_id); - if (item.is_borrow) { - this.failure('error, the book has been loaned'); - } - await BookService.findByIdAndUpdate(item.id, {is_borrow: true}); - await this.updateByCondition({_id: id}, {state: 2, $push: {message: {request_msg: '', reply_msg: content, create_time: new Date()}}}); - return this.success('operator success'); - } - - /** - * return book - * - * @param {*} id - * @memberof BorrowService - */ - async Return(id) { - const info = await this.findById(id); - if (!info) { - this.failure('error:book not found'); - } - await BookService.findByIdAndUpdate(info.book_id, {is_borrow: false}); - await this.updateByCondition({_id: id}, {state: 4, $push: {message: {request_msg: 'return books', reply_msg: '', create_time: new Date()}}}); - return this.success('return success'); - } -} - -export default new BorrowService(); diff --git a/server/src/service/CategoryService.js b/server/src/service/CategoryService.js deleted file mode 100644 index dd096bc..0000000 --- a/server/src/service/CategoryService.js +++ /dev/null @@ -1,10 +0,0 @@ -import {ModelCategory} from '../model/model'; -import BaseService from './BaseService'; - -class CategoryService extends BaseService { - constructor() { - super(ModelCategory); - } -} - -export default new CategoryService(); diff --git a/server/src/service/UserService.js b/server/src/service/UserService.js deleted file mode 100644 index 90e5ea6..0000000 --- a/server/src/service/UserService.js +++ /dev/null @@ -1,105 +0,0 @@ -import { ModelUser } from '../model/model' -import BaseService from './BaseService' -import jwt from 'jsonwebtoken'; -import cfg from './../config' - -class UserService extends BaseService { - constructor() { - super(ModelUser) - } - - - /** - * user signup - * - * @param {*} data - * @return {*} - * @memberof UserService - */ - async SignUp(data) { - const { username, email, password, confirmPwd, address, zip_code } = data; - if (!username) { - this.failure('username is not empty') - } - if (!email) { - this.failure('email is not empty') - } - - if (! /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(email)) { - this.failure('email Incorrect format'); - } - - if (!password) { - this.failure('password is not empty') - } - if (confirmPwd != password) { - this.failure('incorrect password input twice') - } - if (!address) { - this.failure('address is not empty') - } - // judge email is exists - const info = await this.findOne({ email }) - if (info) { - this.failure('email exists'); - } - await this.create({ username, email, password, address, zip_code }) - return this.success('singup success') - } - - /** - * check token - * - * @param {*} token - * @return {*} - * @memberof UserService - */ - async CheckToken(token) { - return new Promise((resolve, reject) => { - jwt.verify(token, cfg.jwtKey, function (err, decoded) { - if (err) { - resolve([true, null]); - } else { - resolve([false, decoded.info]) - } - }); - return false; - }) - } - - /** - * user singin - * - * @param {*} data - * @return {*} - * @memberof UserService - */ - async UserSingin(data) { - const { email, password } = data; - if (!email) { - this.failure('email is not empty') - } - if (!password) { - this.failure('password is not empty') - } - - if (! /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(email)) { - this.failure('email Incorrect format'); - } - - const info = await this.findOne({ email, password }) - if (!info) { - this.failure('invalid username or password'); - } - - delete info.password - delete info.update_time - delete info.create_time - - info.token = jwt.sign({ info }, cfg.jwtKey, { expiresIn: "24h" }); - - return this.success(info) - } -} - -export default new UserService() \ No newline at end of file