Skip to content

Commit

Permalink
fixup! refactor(coap-server): refactor request handling
Browse files Browse the repository at this point in the history
  • Loading branch information
JKRhb committed Jul 26, 2023
1 parent de07c04 commit f635d96
Showing 1 changed file with 34 additions and 23 deletions.
57 changes: 34 additions & 23 deletions packages/binding-coap/src/coap-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,16 +521,7 @@ export default class CoapServer implements ProtocolServer {
res: OutgoingMessage,
affordanceKey: string
) {
const listener = async (content: Content) => {
try {
this.streamContentResponse(res, content, { end: true });
} catch (err) {
error(
`CoapServer on port ${this.getPort()} got internal error on observe '${req.url}': ${err.message}`
);
this.sendResponse(res, "5.00", err.message);
}
};
const listener = this.createContentListener(req, res, this.PROPERTY_DIR, affordanceKey);

try {
await thing.handleObserveProperty(affordanceKey, listener, null);
Expand All @@ -550,6 +541,38 @@ export default class CoapServer implements ProtocolServer {
setTimeout(() => thing.handleUnobserveProperty(affordanceKey, listener, null), 60 * 60 * 1000);
}

private createContentListener(
req: IncomingMessage,
res: OutgoingMessage,
affordanceType: string,
affordanceKey: string
) {
return async (content: Content) => {
try {
debug(
`CoapServer on port ${this.getPort()} sends notification to ${Helpers.toUriLiteral(
req.rsinfo.address
)}:${req.rsinfo.port}`
);
this.streamContentResponse(res, content, { end: true });
} catch (err) {
const code = "5.00";

if (affordanceType === this.EVENT_DIR) {
debug(`CoapServer on port ${this.getPort()} failed '${affordanceKey}' subscription`);
this.sendResponse(res, code, "Subscription to event failed");
} else {
debug(
`CoapServer on port ${this.getPort()} got internal error on observe '${req.url}': ${
err.message
}`
);
this.sendResponse(res, code, err.message);
}
}
};
}

private async handleWriteProperty(
property: PropertyElement,
req: IncomingMessage,
Expand Down Expand Up @@ -681,19 +704,7 @@ export default class CoapServer implements ProtocolServer {
contentType
);

const listener = async (value: Content) => {
try {
debug(
`CoapServer on port ${this.getPort()} sends '${affordanceKey}' notification to ${Helpers.toUriLiteral(
req.rsinfo.address
)}:${req.rsinfo.port}`
);
this.streamContentResponse(res, value);
} catch (err) {
debug(`CoapServer on port ${this.getPort()} failed '${affordanceKey}' subscription`);
this.sendResponse(res, "5.00", `Subscription to event failed`);
}
};
const listener = this.createContentListener(req, res, this.EVENT_DIR, affordanceKey);

try {
await thing.handleSubscribeEvent(affordanceKey, listener, interactionOptions);
Expand Down

0 comments on commit f635d96

Please sign in to comment.