1 |
|
2 | const Model = require("./Model")
|
3 | const Stream = require("./Stream")
|
4 | const Action = require("./Action")
|
5 | const Settings = require("./Settings")
|
6 |
|
7 | class Device extends Model {
|
8 |
|
9 | defaultFields() {
|
10 | return {
|
11 | userId: {
|
12 | type: String,
|
13 | required: true
|
14 | },
|
15 | id: {
|
16 | type: String,
|
17 | required: true
|
18 | },
|
19 | name: { type: String, required: true },
|
20 | description: String,
|
21 | createdAt: {
|
22 | type: Date,
|
23 | transform: (raw) => new Date(raw * 1000)
|
24 | },
|
25 | updatedAt: {
|
26 | type: Date,
|
27 | transform: (raw) => new Date(raw * 1000)
|
28 | },
|
29 | domain: String,
|
30 | properties: Object,
|
31 | settings: {
|
32 | type: Settings,
|
33 | default: () => new Settings()
|
34 | },
|
35 | streams: {
|
36 | listOf: Stream,
|
37 | required: true,
|
38 | default: {},
|
39 | transform: (stream, name) => {
|
40 |
|
41 | if(!stream.channels && typeof stream === "object") {
|
42 |
|
43 | if (stream["dynamic"] === true) {
|
44 | stream.channels = {}
|
45 | }
|
46 | else {
|
47 | stream = {
|
48 | channels: stream
|
49 | }
|
50 | }
|
51 | }
|
52 |
|
53 | if(name) {
|
54 | stream.name = name
|
55 | }
|
56 |
|
57 | return stream
|
58 | }
|
59 | },
|
60 | actions: {
|
61 | listOf: Action,
|
62 | required: true,
|
63 | default: {},
|
64 | transform: (action, name) => {
|
65 |
|
66 | if(typeof action === "string") {
|
67 | let a = action.toString().toLowerCase()
|
68 | a = a.replace(' ', '_')
|
69 | action = {
|
70 | name: action,
|
71 | id: a
|
72 | }
|
73 | }
|
74 |
|
75 | if(name) {
|
76 | action.name = name
|
77 | let a = action.name.toString().toLowerCase()
|
78 | a = a.replace(' ', '_')
|
79 | action.id = a
|
80 | }
|
81 |
|
82 | return action
|
83 | }
|
84 | }
|
85 | }
|
86 | }
|
87 |
|
88 | fromJSON(json) {
|
89 | this.arrayToObject("actions", "name", json)
|
90 | this.arrayToObject("streams", "name", json)
|
91 | super.fromJSON(json)
|
92 | }
|
93 |
|
94 | afterConstructor() {
|
95 |
|
96 | if(this.json.streams) {
|
97 | Object.keys(this.json.streams).forEach((name) => {
|
98 | this.json.streams[name].setDevice(this)
|
99 | })
|
100 | }
|
101 |
|
102 | if(this.json.actions) {
|
103 | Object.keys(this.json.actions).forEach((name) => {
|
104 | this.json.actions[name].setDevice(this)
|
105 | })
|
106 | }
|
107 |
|
108 | }
|
109 |
|
110 | getStream(name) {
|
111 | return this.streams[name] || null
|
112 | }
|
113 |
|
114 | setStream(stream) {
|
115 | this.streams[stream.name] = new Stream(stream)
|
116 | }
|
117 |
|
118 | getAction(name) {
|
119 | return this.actions[name] || null
|
120 | }
|
121 |
|
122 | setAction(action) {
|
123 | this.actions[action.name] = new Action(action)
|
124 | }
|
125 |
|
126 | }
|
127 |
|
128 | module.exports = Device
|