This repository has been archived by the owner on Feb 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (57 loc) · 1.62 KB
/
index.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
var barista = new require('barista').Router
var util = require('util')
var fs = require('fs')
var path = require('path')
var debug = require('debug')('koa-barista')
// Export
module.exports = Router
/**
* Router that extends barista router
*
* @param {Object} Options List of options
*/
function Router(directory) {
this.directory = directory || ''
barista.call(this)
}
// Inherit from barista
util.inherits(Router, barista)
/**
* Callback method for koa middleware
*
* @return {Function} Returns generator function
*/
Router.prototype.callback = function() {
var self = this
return function *router(next) {
// Try to get the first match
var match = self.first(this.request.url, this.request.method)
// Add router to context
self.match = match;
this.router = self;
// No match found
if (match === false) {
debug('no match found for url: "%s"', this.request.url)
yield next
return
}
// Try to get the controller file
var dir = self.directory
var filename = path.join(dir, match.controller + '.js')
if (!fs.existsSync(filename)) {
debug('controller file does not exist: "%s"', match.controller)
yield next
return
}
// Load controller and check the action method
var controller = require(filename)
if (typeof controller[match.action] === 'function') {
debug('route url to controller "%s" and action "%s', controller, match.action)
yield controller[match.action]
return
}
// Action not found
debug('action "%s" in controller "%s" not found', match.action, controller)
yield next
}
}