-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
61 lines (53 loc) · 1.5 KB
/
Copy pathmain.js
File metadata and controls
61 lines (53 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser')
const config = require('config')
const db = require('./db')
const app = new Koa();
const router = new Router()
// Error handling
app.use(async (ctx, next) => {
try {
await next();
} catch (e) {
const resError = {
code: 500,
message: e.message,
errors: e.errors
};
if (e instanceof Error) {
Object.assign(resError, {stack: e.stack});
}
Object.assign(ctx, {body: resError, status: e.status || 500});
}
});
app.use(bodyParser());
router.get('/', (ctx) => ctx.body = {hello: 'world'})
router.get('/users', async (ctx, next) => {
ctx.body = await db.User.find();
});
router.post('/users', async (ctx, next) => {
const data = ctx.request.body;
ctx.body = await db.User.insertOne(data);
});
router.get('/users/:username', async (ctx, next) => {
const username = ctx.params.username;
ctx.body = await db.User.findOne({username: username});
});
router.patch('/users/:username', async (ctx, next) => {
const username = ctx.params.username;
ctx.body = await db.User.updateOne({username: username}, ctx.request.body);
});
router.get('/top10', async (ctx, next) => {
ctx.body = await db.User.find(null, 10, {score: -1});
});
app.use(router.routes())
db.connect()
.then(() => {
app.listen(config.port, () => {
console.info(`Listening to http://localhost:${config.port}`);
});
})
.catch((err) => {
console.error('ERROR:', err)
});