-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpin.js
91 lines (69 loc) · 1.89 KB
/
pin.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
86
87
88
89
90
91
'use strict'
var Jsonic = require('jsonic')
var _ = require('lodash')
function Pin () {}
Pin.preload = function () {
var seneca = this
seneca.decorate('pin', api_pin)
seneca.on('ready', () => {
seneca.root.emit('pin')
seneca.root.emit('after-pin')
})
return {
name: 'pin'
}
}
module.exports = Pin
function api_pin (pattern, pinopts) {
var thispin = this
var so = thispin.options()
pattern = _.isString(pattern) ? Jsonic(pattern) : pattern
var methodkeys = []
for (var key in pattern) {
if (/[\*\?]/.exec(pattern[key])) {
methodkeys.push(key)
}
}
function make_pin (pattern) {
var api = {
toString: function () {
return 'pin:' + thispin.util.pattern(pattern) + '/' + thispin
}
}
var calcPin = function () {
var methods = thispin.private$.actrouter.list(pattern)
methods.forEach(function (method) {
var mpat = method.match
var methodname = ''
for (var mkI = 0; mkI < methodkeys.length; mkI++) {
methodname += ((mkI > 0 ? '_' : '')) + mpat[methodkeys[mkI]]
}
api[methodname] = function (args, cb) {
var si = this && this.seneca ? this : thispin
var fullargs = _.extend({}, args, mpat)
si.act(fullargs, cb)
}
api[methodname].pattern$ = method.match
api[methodname].name$ = methodname
})
if (pinopts && pinopts.include) {
for (var i = 0; i < pinopts.include.length; i++) {
var methodname = pinopts.include[i]
if (thispin[methodname]) {
api[methodname] = thispin.delegate(thispin, thispin[methodname])
}
}
}
}
var opts = {}
_.defaults(opts, pinopts, so.pin)
if (thispin.private$._isReady || opts.immediate) {
calcPin()
}
else {
thispin.once('pin', calcPin)
}
return api
}
return make_pin(pattern)
}