MCPcopy Index your code
hub / github.com/WebThingsIO/webthing-node / ws

Method ws

lib/server.ts:204–328  ·  view source on GitHub ↗

* Handle a websocket request. * * @param {Object} ws The websocket object * @param {Object} req The request object

(ws: import('ws'), req: express.Request)

Source from the content-addressed store, hash-verified

202 * @param {Object} req The request object
203 */
204 ws(ws: import('ws'), req: express.Request): void {
205 const thing = this.getThing(req);
206 if (thing === null) {
207 ws.send(JSON.stringify({
208 messageType: 'error',
209 data: {
210 status: '404 Not Found',
211 message: 'The requested thing was not found',
212 },
213 }));
214 return;
215 }
216
217 thing.addSubscriber(ws);
218
219 ws.on('error', () => thing.removeSubscriber(ws));
220 ws.on('close', () => thing.removeSubscriber(ws));
221
222 ws.on('message', (msg) => {
223 let message: {
224 messageType: string,
225 data: {[name: string]: any},
226 };
227 try {
228 message = JSON.parse(msg as string);
229 } catch (e1) {
230 try {
231 ws.send(JSON.stringify({
232 messageType: 'error',
233 data: {
234 status: '400 Bad Request',
235 message: 'Parsing request failed',
236 },
237 }));
238 } catch (e2) {
239 // do nothing
240 }
241
242 return;
243 }
244
245 if (!message.hasOwnProperty('messageType') ||
246 !message.hasOwnProperty('data')) {
247 try {
248 ws.send(JSON.stringify({
249 messageType: 'error',
250 data: {
251 status: '400 Bad Request',
252 message: 'Invalid message',
253 },
254 }));
255 } catch (e) {
256 // do nothing
257 }
258
259 return;
260 }
261

Callers 1

constructorMethod · 0.95

Calls 8

sendMethod · 0.80
addSubscriberMethod · 0.80
removeSubscriberMethod · 0.80
setPropertyMethod · 0.80
addEventSubscriberMethod · 0.80
getThingMethod · 0.45
performActionMethod · 0.45
startMethod · 0.45

Tested by

no test coverage detected