From 5a6be2c734e0c03e9b55415e3dd8638b3998bf26 Mon Sep 17 00:00:00 2001 From: shaoh4 Date: Tue, 22 Dec 2020 19:49:40 +0800 Subject: [PATCH] backend add test --- .gitignore | 1 + client/src/App.test.js | 15 +- client/src/actions/index.js | 4 +- client/src/components/component.mynav.js | 2 +- client/src/test/component.test.js | 30 ++ server/.babelrc | 15 +- server/api.test.js | 364 +++++++++++++++++++++++ server/index.js | 3 +- server/jest.config.js | 3 + server/package.json | 7 +- server/src/api/api.book.js | 3 +- server/src/api/api.borrow.js | 1 + server/src/config.js | 14 +- server/src/main.js | 31 +- server/src/service/BaseService.js | 2 +- server/src/service/UserService.js | 2 +- 16 files changed, 464 insertions(+), 33 deletions(-) create mode 100644 client/src/test/component.test.js create mode 100644 server/api.test.js create mode 100644 server/jest.config.js diff --git a/.gitignore b/.gitignore index f71bbb6..b6f21e7 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ server/uploads/ server/public/ server/yarn.lock client/package-lock.json +package-lock.json diff --git a/client/src/App.test.js b/client/src/App.test.js index 1f03afe..650c607 100644 --- a/client/src/App.test.js +++ b/client/src/App.test.js @@ -1,8 +1,17 @@ -import { render, screen } from '@testing-library/react'; import App from './App'; +import {render, screen} from '@testing-library/react'; +import {createStore, applyMiddleware, compose} from 'redux'; +import reducers from './reducers'; +const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; +import {Provider} from 'react-redux'; +import reduxThunk from 'redux-thunk'; test('renders learn react link', () => { - render(); - const linkElement = screen.getByText(/learn react/i); + render( + + + , + ); + const linkElement = screen.getByText(/WELCOME TO BORROW PLATFORM/i); expect(linkElement).toBeInTheDocument(); }); diff --git a/client/src/actions/index.js b/client/src/actions/index.js index 9fcda4d..e6fa0d9 100644 --- a/client/src/actions/index.js +++ b/client/src/actions/index.js @@ -5,10 +5,10 @@ const ApiMap = { 'development': 'http://127.0.0.1:4900', 'production': '', } -console.log('process.env.NODE_ENV:', process.env.NODE_ENV); +// console.log('process.env.NODE_ENV:', process.env.NODE_ENV); export const ApiService = ApiMap[process.env.NODE_ENV] || ''; -console.log('api:', ApiService) +// console.log('api:', ApiService) export const TypeMap = { LOADING: 'COMMON_LOADING', diff --git a/client/src/components/component.mynav.js b/client/src/components/component.mynav.js index 50a0f24..f428105 100644 --- a/client/src/components/component.mynav.js +++ b/client/src/components/component.mynav.js @@ -36,7 +36,7 @@ class MyNav extends React.Component { render() { const { role } = this.props.user.info || {}; - console.log('role:', role) + // console.log('role:', role) return (
diff --git a/client/src/test/component.test.js b/client/src/test/component.test.js new file mode 100644 index 0000000..27d84a4 --- /dev/null +++ b/client/src/test/component.test.js @@ -0,0 +1,30 @@ +import React from 'react'; +import {render, fireEvent, screen} from '@testing-library/react'; +import {createStore, applyMiddleware, compose} from 'redux'; +import reducers from '../reducers'; +const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; +import {Provider} from 'react-redux'; +import reduxThunk from 'redux-thunk'; +import {Router, Route, Switch} from 'react-router-dom'; +import {createBrowserHistory} from 'history'; +const history = createBrowserHistory(); + +import MyNav from '../components/component.mynav'; + +it('shows success message after confirm button is clicked', () => { + const {getByText} = render( + + + + + , + ); + expect(screen.getByText(/My Book List/i)).toBeInTheDocument(); + expect(screen.getByText(/Release/i)).toBeInTheDocument(); + expect(screen.getByText(/Request List/i)).toBeInTheDocument(); + expect(screen.getByText(/Borrow List/i)).toBeInTheDocument(); + + // fireEvent.click(getByText('Confirm')); + + // expect(getByText('Confirmed!')).toBeInTheDocument(); +}); diff --git a/server/.babelrc b/server/.babelrc index e3beb4b..88fbb7f 100644 --- a/server/.babelrc +++ b/server/.babelrc @@ -1,11 +1,14 @@ { "presets": [ [ - "@babel/preset-env" + "@babel/preset-env", + { + "targets": { + "node": "current" + } + } ] - ], - "plugins": [ - ["transform-class-properties", { "spec": true }] - ] -} \ No newline at end of file + "plugins": [["transform-class-properties", {"spec": true}]] + +} diff --git a/server/api.test.js b/server/api.test.js new file mode 100644 index 0000000..68d4440 --- /dev/null +++ b/server/api.test.js @@ -0,0 +1,364 @@ +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 index 77fde49..80ac181 100644 --- a/server/index.js +++ b/server/index.js @@ -1,4 +1,5 @@ require('@babel/core'); require('@babel/register'); require('@babel/polyfill'); -require("./src/main"); \ No newline at end of file +const app = require('./src/main'); +module.exports = app; diff --git a/server/jest.config.js b/server/jest.config.js new file mode 100644 index 0000000..f2837b4 --- /dev/null +++ b/server/jest.config.js @@ -0,0 +1,3 @@ +module.exports = { + testEnvironment: 'node' +}; \ No newline at end of file diff --git a/server/package.json b/server/package.json index 938d2b6..5062f3f 100644 --- a/server/package.json +++ b/server/package.json @@ -5,7 +5,8 @@ "license": "MIT", "scripts": { "dev": "better-npm-run start-dev", - "test": "echo \"Error: no test specified\" && exit 1" + "test1": "jest --runInBand --testTimeout=5000 --coverage --detectOpenHandles", + "test": "jest --runInBand --testTimeout=5000 --coverage" }, "betterScripts": { "start-dev": { @@ -32,9 +33,11 @@ "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" + "nodemon": "^2.0.6", + "supertest": "^6.0.1" } } diff --git a/server/src/api/api.book.js b/server/src/api/api.book.js index 481b475..8ca67cd 100644 --- a/server/src/api/api.book.js +++ b/server/src/api/api.book.js @@ -101,8 +101,7 @@ router const data = request.body; data.file = request.file; data.userInfo = request.userInfo; - - console.log(data); + const info = await BookService.UpdateBook(id, request.body); response.json(info); } catch (ex) { diff --git a/server/src/api/api.borrow.js b/server/src/api/api.borrow.js index 864739b..875558a 100644 --- a/server/src/api/api.borrow.js +++ b/server/src/api/api.borrow.js @@ -10,6 +10,7 @@ router const userInfo = request.userInfo; if (!userInfo) { response.status('401').json({code: 401, data: 'Unauthorized'}); + return; } await next(); } catch (ex) { diff --git a/server/src/config.js b/server/src/config.js index c09f828..6f639ae 100644 --- a/server/src/config.js +++ b/server/src/config.js @@ -1,4 +1,4 @@ -module.exports = { +const config = { development: { dbConn: 'mongodb://BorrowBook:BorrowBook_BorrowBook@175.24.101.94/BorrowBook', jwtKey: 'shaoh4_304CEM@coventry.ac.uk', @@ -6,5 +6,15 @@ module.exports = { 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', } -}[process.env.NODE_ENV || 'development'] \ No newline at end of file +} + +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 index 4a4471c..a63a1cb 100644 --- a/server/src/main.js +++ b/server/src/main.js @@ -15,9 +15,10 @@ const port = process.env.PORT || 4900; 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); + 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); } @@ -27,16 +28,16 @@ const app = express(); const staticPath = path.join(__dirname, '../public'); // create static resource directory if (!fs.existsSync(staticPath)) { - fs.mkdirSync(staticPath, { recursive: true }); + fs.mkdirSync(staticPath, {recursive: true}); } app.use(express.static(staticPath)); app.use(express.json()); -app.use(express.urlencoded({ extended: false })); +app.use(express.urlencoded({extended: false})); app.use(bodyParser.json()); app.use( session({ - cookie: { secure: true, maxAge: 60 * 60 * 24, httpOnly: true, path: '/' }, + cookie: {secure: true, maxAge: 60 * 60 * 24, httpOnly: true, path: '/'}, secret: 'nodex-express@!@#$1234', resave: false, saveUninitialized: false, @@ -45,7 +46,7 @@ app.use( // console print request method and url path; app.use(async function (req, res, next) { - const { headers, method, url } = req; + 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'); @@ -56,7 +57,7 @@ app.use(async function (req, res, next) { req.token = headers.token; const [isExpire, userInfo] = await UserService.CheckToken(req.token); if (!isExpire) { - req.userInfo = userInfo + req.userInfo = userInfo; } else { req.token = ''; } @@ -70,7 +71,7 @@ router(app); app.use('/', (req, res, next) => { res.statusCode = 404; - res.send({ code: 404, msg: 'method not found' }); + res.send({code: 404, msg: 'method not found'}); next(); }); @@ -81,7 +82,7 @@ app.use(function (err, req, res, next) { } console.log('----------------------error----------', err.status); console.log(err); - res.status(err.status || 500).send(JSON.stringify({ code: err.status || 500, msg: err.message })); + res.status(err.status || 500).send(JSON.stringify({code: err.status || 500, msg: err.message})); }); app.set('port', port); @@ -112,7 +113,7 @@ server.on('error', (error) => { // create mongodb connection const MongoDbConn = () => { - mongoose.connect(cfg.dbConn, { useUnifiedTopology: true, useNewUrlParser: true }, function (err) { + mongoose.connect(cfg.dbConn, {useUnifiedTopology: true, useNewUrlParser: true}, function (err) { if (err) throw err; console.log('Connected to mongodb success'); }); @@ -121,7 +122,11 @@ const MongoDbConn = () => { // listening server.on('listening', () => { printLog(`http://127.0.0.1:${port}/api`); - MongoDbConn(); + try { + MongoDbConn(); + } catch (ex) { + // + } }); process.on('unhandledRejection', (err, b, next) => { @@ -130,3 +135,5 @@ process.on('unhandledRejection', (err, b, next) => { next(); } }); + +export default app; diff --git a/server/src/service/BaseService.js b/server/src/service/BaseService.js index 3d9516c..150789f 100644 --- a/server/src/service/BaseService.js +++ b/server/src/service/BaseService.js @@ -54,7 +54,7 @@ export default class BaseService { return list ? JSON.parse(JSON.stringify(list)) : []; } catch (ex) { this.log(ex); - return []; + this.failure(ex.message) } } diff --git a/server/src/service/UserService.js b/server/src/service/UserService.js index 93e055c..90e5ea6 100644 --- a/server/src/service/UserService.js +++ b/server/src/service/UserService.js @@ -80,7 +80,7 @@ class UserService extends BaseService { this.failure('email is not empty') } if (!password) { - this.failure('pssword is not empty') + 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)) {