forked from mitipi/serverless-iot-offline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (82 loc) · 2.64 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
84
85
86
87
88
89
90
91
92
'use strict';
const _ = require('lodash')
const createBroker = require('./broker')
const createShadowService = require('./shadowService')
const iotMock = require('./iotMock')
const ruleHandler = require('./ruleHandler')
const {seedShadows, seedPolicies} = require('./util')
const defaultOpts = {
host: 'localhost',
location: '.',
port: 1883,
httpPort: 1884,
noStart: false,
skipCacheInvalidation: false
}
class ServerlessIotPlugin {
constructor (serverless, options) {
this.serverless = serverless
this.log = serverless.cli.log.bind(serverless.cli)
this.service = serverless.service
this.options = options
this.provider = 'aws'
this.topics = {}
this.commands = {
iot: {
commands: {
start: {
usage: 'Start local Iot broker.',
lifecycleEvents: ['startHandler'],
options: {
host: {
usage: 'host name to listen on. Default: localhost',
// match serverless-offline option shortcuts
shortcut: 'o'
},
port: {
usage: 'MQTT port to listen on. Default: 1883',
shortcut: 'p'
},
httpPort: {
usage: 'http port for client connections over WebSockets. Default: 1884',
shortcut: 'h'
},
skipCacheInvalidation: {
usage: 'Tells the plugin to skip require cache invalidation. A script reloading tool like Nodemon might then be needed',
shortcut: 'c',
},
}
}
}
}
}
this.hooks = {
'iot:start:startHandler': this.startHandler.bind(this),
'before:offline:start:init': this.startHandler.bind(this),
'before:offline:start': this.startHandler.bind(this),
'before:offline:start:end': this.endHandler.bind(this),
}
}
startHandler () {
this.options = _.merge({}, defaultOpts, _.get(this.service, 'custom.iot', {}), this.options)
this.mqttBroker = createBroker({
host: this.options.host,
port: this.options.port,
http: {
host: this.options.host,
port: this.options.httpPort,
bundle: true
}
}, this.log)
const {client, redisClient} = createShadowService(this.options, this.log)
seedShadows(this.options.seedShadows, redisClient)
seedPolicies(this.options.seedPolicies, redisClient)
iotMock(client, redisClient)
ruleHandler(this.options, this.service, this.serverless, this.log)
}
endHandler () {
this.log('Stopping Iot broker')
this.mqttBroker.close()
}
}
module.exports = ServerlessIotPlugin