-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (69 loc) · 1.98 KB
/
server.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import koa from 'koa';
import Router from 'koa-router';
import qs from 'koa-qs';
import bodyParser from 'koa-bodyparser';
import mongoose from 'mongoose';
import {graphql} from 'graphql';
import schema from './schema';
import serve from 'koa-static';
import mount from 'koa-mount';
import Employee from './models/employee';
let port = process.env.PORT || 3000;
let routes = new Router();
var app = koa();
app.use(bodyParser());
app.use(mount('/public', serve(__dirname+'/public')));
// support nested query tring params
qs(app);
let mongoUri = process.env.MONGO_URI || 'mongodb://mongo:27017/graphql';
if (process.env.NODE_ENV !== 'test') {
mongoose.connect(mongoUri);
}
routes.get('/data', function* () {
var query = this.query.query;
var params = this.query.params;
var resp = yield graphql(schema, query, '', params);
if (resp.errors) {
this.status = 400;
this.body = {
errors: resp.errors
};
return;
}
this.body = resp;
});
routes.get('/api/employees', function* () {
var q = this.query.q || undefined;
if (q) {
var allEmployees = yield Employee.find({});
var employees = allEmployees.filter((employee) => {
var searchKey = employee.firstName + ' ' + employee.lastName + employee.title;
return searchKey.toLowerCase().indexOf(q.toLowerCase()) !== -1;
});
} else {
var employees = yield Employee.find({});
}
var resp = {total : employees.length, employees: employees};
this.body = resp;
});
routes.get('/api/employees/:id', function* (){
var employee = yield Employee.findOne({id: this.params.id});
this.body = employee;
});
routes.post('/data', function* () {
var payload = this.request.body;
var resp = yield graphql(schema, payload.query, '', payload.params);
if (resp.errors) {
this.status = 400;
this.body = {
errors: resp.errors
};
return;
}
this.body = resp;
});
app.use(routes.middleware());
app.listen(port, () => {
console.log('app is listening on ' + port);
});
module.exports = app;