Added better API errors and stuff
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
exports[`test should require authentication 1`] = `
|
||||
Object {
|
||||
"message": "Authentication required"
|
||||
"error": "Authentication required",
|
||||
"success": false
|
||||
}
|
||||
`;
|
||||
|
||||
@ -11,6 +12,7 @@ Object {
|
||||
"id": "86fde1d4-0050-428f-9f0b-0bf77f8bdf61",
|
||||
"name": "User 1",
|
||||
"username": "user1"
|
||||
}
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
`;
|
||||
|
@ -14,6 +14,7 @@ import apiKeys from './apiKeys';
|
||||
import validation from './middlewares/validation';
|
||||
import methodOverride from '../middlewares/methodOverride';
|
||||
import cache from '../middlewares/cache';
|
||||
import apiWrapper from './middlewares/apiWrapper';
|
||||
|
||||
const api = new Koa();
|
||||
const router = new Router();
|
||||
@ -39,7 +40,10 @@ api.use(async (ctx, next) => {
|
||||
ctx.app.emit('error', err, ctx);
|
||||
}
|
||||
|
||||
ctx.body = { message };
|
||||
ctx.body = {
|
||||
success: false,
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@ -47,6 +51,7 @@ api.use(bodyParser());
|
||||
api.use(methodOverride());
|
||||
api.use(cache());
|
||||
api.use(validation());
|
||||
api.use(apiWrapper());
|
||||
|
||||
router.use('/', auth.routes());
|
||||
router.use('/', user.routes());
|
||||
@ -59,9 +64,4 @@ router.use('/', apiKeys.routes());
|
||||
// allow middleware to catch any routes which were not explicitly defined.
|
||||
api.use(router.routes());
|
||||
|
||||
// API 404 handler
|
||||
api.use(async () => {
|
||||
throw httpErrors.NotFound();
|
||||
});
|
||||
|
||||
export default api;
|
||||
|
12
server/api/middlewares/apiWrapper.js
Normal file
12
server/api/middlewares/apiWrapper.js
Normal file
@ -0,0 +1,12 @@
|
||||
export default function apiWrapper(_options) {
|
||||
return async function apiWrapperMiddleware(ctx, next) {
|
||||
await next();
|
||||
|
||||
const success = ctx.status < 400;
|
||||
|
||||
ctx.body = {
|
||||
...ctx.body,
|
||||
success,
|
||||
};
|
||||
};
|
||||
}
|
Reference in New Issue
Block a user