]>
git.r.bdr.sh - rbdr/dasein/blob - lib/dasein.js
3a537bd8ccdf9d11b33e0d888bc269cfa5b8b838
3 const Koa
= require('koa');
4 const KoaBodyParser
= require('koa-bodyparser');
5 const KoaJwt
= require('koa-jwt');
6 const KoaRoute
= require('koa-route');
7 const KoaSend
= require('koa-send');
8 const KoaStatic
= require('koa-static');
9 const Path
= require('path');
11 const AuthHandler
= require('./handlers/auth');
12 const PostsHandler
= require('./handlers/posts');
16 internals
.k401Location
= '/401.html';
17 internals
.kMainLocation
= '/';
20 * The Dasein class is the main entry point for the application.
23 * @param {Dasein.tConfiguration} config the initialization options to
26 module
.exports
= internals
.Dasein
= class Dasein
{
30 Object
.assign(this, config
);
34 * Initializes the application and starts listening. Also prints a
35 * nice robotic banner with information.
43 this._initializeServer();
47 return Promise
.resolve();
50 // Initializes the Koa application and all the handlers.
58 this._app
.use(KoaStatic(this.staticDirectory
));
59 this._app
.use(KoaBodyParser());
63 this._app
.use(function * (next
) {
69 this.status
= err
.status
|| 500;
76 if (response
.status
=== 401) {
77 response
.error
=== 'Protected resource, use Authorization header to get access';
82 this.app
.emit('error', err
, this);
86 this._app
.use(KoaJwt({
87 secret: this.jwt
.secret
,
91 this._initializeAuthRoutes();
92 this._initializePostsRoutes();
94 this._app
.use(function * () {
96 yield KoaSend(this, Path
.join(self
.staticDirectory
, 'index.html'));
101 // Initialize routes for auth
103 _initializeAuthRoutes() {
105 const authHandler
= new AuthHandler({
107 twitter: this.twitter
109 this._app
.use(KoaRoute
.get('/api/auth/login', authHandler
.login()));
110 this._app
.use(KoaRoute
.post('/api/auth/callback', authHandler
.callback()));
113 // Initialize routes for posts
115 _initializePostsRoutes() {
117 const postsHandler
= new PostsHandler({
121 this._app
.use(KoaRoute
.get('/api/posts', postsHandler
.findAll()));
122 this._app
.use(KoaRoute
.get('/api/posts/:id', postsHandler
.find()));
123 this._app
.use(KoaRoute
.post('/api/posts', postsHandler
.create()));
124 this._app
.use(KoaRoute
.delete('/api/posts/:id', postsHandler
.delete()));
132 this._app
.listen(this.port
);
135 // Prints the banner.
141 console
.log(' +-----+');
142 console
.log(` | o o | - Listening Gladly, Try me on port: ${this.port}`);
143 console
.log(' +-----+');
144 console
.log(' +---------+');
145 console
.log(' /| [][] |\\');
146 console
.log(' || | |');
147 console
.log(' || | \\c');
148 console
.log(' ^+---------+');
149 console
.log(' (.) ');