/ src / app.js
app.js
 1  import log from 'loglevel'
 2  import Koa from 'koa'
 3  import JSON from 'koa-json'
 4  import Logger from 'koa-logger'
 5  import JsonError from 'koa-json-error'
 6  import JoiRouter from 'koa-joi-router'
 7  import BodyParser from 'koa-bodyparser'
 8  
 9  const App = ({ghc, schema}) => {
10    const app = new Koa()
11    const router = new JoiRouter()
12  
13    app.on('error', (err, ctx) => {
14      /* istanbul ignore next */
15      console.error('server error', err, ctx)
16    })
17  
18    app.use(Logger((str, args) => log.info(str)))
19       .use(JSON({pretty: true}))
20       .use(JsonError())
21       .use(router.middleware())
22       .use(BodyParser({onerror:console.error}))
23  
24    router.get('/', async (ctx) => {
25      ctx.redirect('https://status.im/')
26    })
27  
28    router.get('/health', async (ctx) => {
29      ctx.body = 'OK'
30    })
31  
32    /* store build and post/update the comment */
33    router.route({
34      method: 'post',
35      path: '/builds/:org/:repo/:pr',
36      validate: {
37        type: 'json',
38        body: schema,
39      },
40      handler: async (ctx) => {
41        await ghc.db.addBuild({
42          ...ctx.params, build: ctx.request.body
43        })
44        await ghc.safeUpdate(ctx.params)
45        ctx.status = 201
46        ctx.body = {status:'ok'}
47      }
48    })
49  
50    /* just re-render the comment */
51    router.post('/builds/:org/:repo/:pr/refresh', async (ctx) => {
52      await ghc.safeUpdate(ctx.params)
53      ctx.status = 201
54      ctx.body = {status:'ok'}
55    })
56  
57    /* list builds for repo+pr */
58    router.get('/builds/:org/:repo/:pr', async (ctx) => {
59      const builds = await ghc.db.getPRBuilds(ctx.params)
60      ctx.body = {count: builds.length, builds}
61    })
62  
63    /* drop builds for repo+pr */
64    router.delete('/builds/:org/:repo/:pr', async (ctx) => {
65      const builds = await ghc.db.removeBuilds(ctx.params)
66      ctx.body = {count: builds.length, builds}
67    })
68  
69    /* list all builds */
70    router.get('/builds', async (ctx) => {
71      const builds = await ghc.db.getBuilds(ctx.params)
72      const keys = Object.keys(builds)
73      ctx.body = {count: keys.length, builds: keys}
74    })
75  
76    /* list all managed comments */
77    router.get('/comments', async (ctx) => {
78      const comments = await ghc.db.getComments()
79      ctx.body = {count: Object.keys(comments).length, comments}
80    })
81  
82    return app
83  }
84  
85  export default App