Skip to content

Commit

Permalink
Merge pull request #1110 from JKRhb/async-promise
Browse files Browse the repository at this point in the history
refactor: remove unnecessary `new Promise` wrappers
  • Loading branch information
relu91 authored Oct 10, 2023
2 parents b705ce3 + 3489ea5 commit 4c3c203
Show file tree
Hide file tree
Showing 16 changed files with 142 additions and 238 deletions.
14 changes: 5 additions & 9 deletions packages/binding-coap/test/coap-server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,8 @@ class CoapServerTest {
},
});

testThing.setActionHandler("try", (input: WoT.InteractionOutput) => {
return new Promise<string>((resolve, reject) => {
resolve("TEST");
});
testThing.setActionHandler("try", async (input: WoT.InteractionOutput) => {
return "TEST";
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down Expand Up @@ -444,11 +442,9 @@ class CoapServerTest {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
testThing.properties.test.forms = [];
testThing.setActionHandler("try", (input: WoT.InteractionOutput, params?: InteractionOptions) => {
return new Promise<string>((resolve, reject) => {
expect(params?.uriVariables).to.deep.equal({ step: 5 });
resolve("TEST");
});
testThing.setActionHandler("try", async (input: WoT.InteractionOutput, params?: InteractionOptions) => {
expect(params?.uriVariables).to.deep.equal({ step: 5 });
return "TEST";
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down
82 changes: 36 additions & 46 deletions packages/binding-file/src/file-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,66 +29,56 @@ export default class FileClient implements ProtocolClient {
return "[FileClient]";
}

public readResource(form: Form): Promise<Content> {
return new Promise<Content>((resolve, reject) => {
const filepath = form.href.split("//");
const resource = fs.createReadStream(filepath[1]);
const extension = path.extname(filepath[1]);
debug(`FileClient found '${extension}' extension`);
let contentType;
if (form.contentType) {
contentType = form.contentType;
} else {
// *guess* contentType based on file extension
contentType = "application/octet-stream";
switch (extension) {
case ".txt":
case ".log":
case ".ini":
case ".cfg":
contentType = "text/plain";
break;
case ".json":
contentType = "application/json";
break;
case ".jsonld":
contentType = "application/ld+json";
break;
default:
warn(`FileClient cannot determine media type of '${form.href}'`);
}
public async readResource(form: Form): Promise<Content> {
const filepath = form.href.split("//");
const resource = fs.createReadStream(filepath[1]);
const extension = path.extname(filepath[1]);
debug(`FileClient found '${extension}' extension`);
let contentType;
if (form.contentType) {
contentType = form.contentType;
} else {
// *guess* contentType based on file extension
contentType = "application/octet-stream";
switch (extension) {
case ".txt":
case ".log":
case ".ini":
case ".cfg":
contentType = "text/plain";
break;
case ".json":
contentType = "application/json";
break;
case ".jsonld":
contentType = "application/ld+json";
break;
default:
warn(`FileClient cannot determine media type of '${form.href}'`);
}
resolve(new Content(contentType, resource));
});
}
return new Content(contentType, resource);
}

public writeResource(form: Form, content: Content): Promise<void> {
return new Promise<void>((resolve, reject) => {
reject(new Error(`FileClient does not implement write`));
});
public async writeResource(form: Form, content: Content): Promise<void> {
throw new Error("FileClient does not implement write");
}

public invokeResource(form: Form, content: Content): Promise<Content> {
return new Promise<Content>((resolve, reject) => {
reject(new Error(`FileClient does not implement invoke`));
});
public async invokeResource(form: Form, content: Content): Promise<Content> {
throw new Error("FileClient does not implement invoke");
}

public unlinkResource(form: Form): Promise<void> {
return new Promise<void>((resolve, reject) => {
reject(new Error(`FileClient does not implement unlink`));
});
public async unlinkResource(form: Form): Promise<void> {
throw new Error("FileClient does not implement unlink");
}

public subscribeResource(
public async subscribeResource(
form: Form,
next: (value: Content) => void,
error?: (error: Error) => void,
complete?: () => void
): Promise<Subscription> {
return new Promise<Subscription>((resolve, reject) => {
reject(new Error(`FileClient does not implement subscribe`));
});
throw new Error("FileClient does not implement subscribe");
}

public async start(): Promise<void> {
Expand Down
41 changes: 17 additions & 24 deletions packages/binding-http/src/http-client-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,36 +148,29 @@ export default class HttpClient implements ProtocolClient {
debug(`HttpClient received headers: ${JSON.stringify(result.headers.raw())}`);
}

public subscribeResource(
public async subscribeResource(
form: HttpForm,
next: (value: Content) => void,
error?: (error: Error) => void,
complete?: () => void
): Promise<Subscription> {
return new Promise<Subscription>((resolve, reject) => {
let internalSubscription: InternalSubscription;
if (form.subprotocol === undefined || form.subprotocol === "longpoll") {
// longpoll or subprotocol is not defined default is longpoll
internalSubscription = new LongPollingSubscription(form, this);
} else if (form.subprotocol === "sse") {
// server sent events
internalSubscription = new SSESubscription(form);
} else {
reject(new Error(`HttpClient does not support subprotocol ${form.subprotocol}`));
return;
}
const defaultSubprotocol = "longpoll";
const subprotocol = form.subprotocol ?? defaultSubprotocol;

let internalSubscription: InternalSubscription;
if (subprotocol === defaultSubprotocol) {
internalSubscription = new LongPollingSubscription(form, this);
} else if (form.subprotocol === "sse") {
// server sent events
internalSubscription = new SSESubscription(form);
} else {
throw new Error(`HttpClient does not support subprotocol ${form.subprotocol}`);
}

internalSubscription
.open(next, error, complete)
.then(() => {
this.activeSubscriptions.set(form.href, internalSubscription);
resolve(
new Subscription(() => {
internalSubscription.close();
})
);
})
.catch((err) => reject(err));
await internalSubscription.open(next, error, complete);
this.activeSubscriptions.set(form.href, internalSubscription);
return new Subscription(() => {
internalSubscription.close();
});
}

Expand Down
28 changes: 12 additions & 16 deletions packages/binding-http/src/http-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,24 +295,20 @@ export default class HttpServer implements ProtocolServer {
}
}

public destroy(thingId: string): Promise<boolean> {
public async destroy(thingId: string): Promise<boolean> {
debug(`HttpServer on port ${this.getPort()} destroying thingId '${thingId}'`);
return new Promise<boolean>((resolve, reject) => {
let removedThing: ExposedThing | undefined;
for (const name of Array.from(this.things.keys())) {
const expThing = this.things.get(name);
if (expThing?.id === thingId) {
this.things.delete(name);
removedThing = expThing;
}
}
if (removedThing) {
info(`HttpServer successfully destroyed '${removedThing.title}'`);
} else {
info(`HttpServer failed to destroy thing with thingId '${thingId}'`);

for (const [name, thing] of this.things.entries()) {
if (thing.id === thingId) {
this.things.delete(name);
info(`HttpServer successfully destroyed '${thing.title}'`);

return true;
}
resolve(removedThing !== undefined);
});
}

info(`HttpServer failed to destroy thing with thingId '${thingId}'`);
return false;
}

private addUrlRewriteEndpoints(form: TD.Form, forms: Array<TD.Form>): void {
Expand Down
12 changes: 3 additions & 9 deletions packages/binding-http/test/http-client-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,10 @@ class TestHttpServer implements ProtocolServer {
}
}

public expose(thing: unknown): Promise<void> {
return new Promise<void>((resolve, reject) => {
resolve();
});
}
public async expose(thing: unknown): Promise<void> {}

public destroy(thingId: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
resolve(false);
});
public async destroy(thingId: string): Promise<boolean> {
return false;
}

public setTestVector(vector: TestVector) {
Expand Down
34 changes: 12 additions & 22 deletions packages/binding-http/test/http-server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import fetch from "node-fetch";

import HttpServer from "../src/http-server";
import Servient, { Content, createLoggers, ExposedThing, Helpers } from "@node-wot/core";
import { DataSchemaValue, InteractionInput, InteractionOptions } from "wot-typescript-definitions";
import { DataSchemaValue, InteractionOptions } from "wot-typescript-definitions";
import chaiAsPromised from "chai-as-promised";
import { Readable } from "stream";
import { MiddlewareRequestHandler } from "../src/http-server-middleware";
Expand Down Expand Up @@ -163,10 +163,8 @@ class HttpServerTest {
test = await value.value();
});

testThing.setActionHandler("try", (input: WoT.InteractionOutput) => {
return new Promise<string>((resolve, reject) => {
resolve("TEST");
});
testThing.setActionHandler("try", async (input: WoT.InteractionOutput) => {
return "TEST";
});

await httpServer.expose(testThing);
Expand Down Expand Up @@ -276,11 +274,9 @@ class HttpServerTest {
},
});
let test: DataSchemaValue;
testThing.setPropertyReadHandler("test", (options) => {
testThing.setPropertyReadHandler("test", async (options) => {
expect(options?.uriVariables).to.deep.equal({ id: "testId" });
return new Promise<InteractionInput>((resolve, reject) => {
resolve(test);
});
return test;
});
testThing.setPropertyWriteHandler("test", async (value, options) => {
expect(options?.uriVariables).to.deep.equal({ id: "testId" });
Expand All @@ -289,11 +285,9 @@ class HttpServerTest {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
testThing.properties.test.forms = [];
testThing.setActionHandler("try", (input: WoT.InteractionOutput, params?: InteractionOptions) => {
return new Promise<string>((resolve, reject) => {
expect(params?.uriVariables).to.deep.equal({ step: 5 });
resolve("TEST");
});
testThing.setActionHandler("try", async (input: WoT.InteractionOutput, params?: InteractionOptions) => {
expect(params?.uriVariables).to.deep.equal({ step: 5 });
return "TEST";
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down Expand Up @@ -339,10 +333,8 @@ class HttpServerTest {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
testThing.properties.test.forms = [];
testThing.setActionHandler("try", (input: WoT.InteractionOutput) => {
return new Promise<string>((resolve, reject) => {
resolve("TEST");
});
testThing.setActionHandler("try", async (input: WoT.InteractionOutput) => {
return "TEST";
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down Expand Up @@ -580,11 +572,9 @@ class HttpServerTest {
},
});
let test: DataSchemaValue;
testThing.setPropertyReadHandler("test", (options) => {
testThing.setPropertyReadHandler("test", async (options) => {
expect(options?.uriVariables).to.deep.equal({ id: "testId", globalVarTest: "test1" });
return new Promise<InteractionInput>((resolve, reject) => {
resolve(test);
});
return test;
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
Expand Down
24 changes: 8 additions & 16 deletions packages/binding-mbus/src/mbus-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,33 +40,25 @@ export default class MBusClient implements ProtocolClient {
return this.performOperation(form) as Promise<Content>;
}

writeResource(form: MBusForm, content: Content): Promise<void> {
return new Promise<void>((resolve, reject) => {
throw new Error("Method not implemented.");
});
async writeResource(form: MBusForm, content: Content): Promise<void> {
throw new Error("Method not implemented.");
}

invokeResource(form: MBusForm, content: Content): Promise<Content> {
return new Promise<Content>((resolve, reject) => {
throw new Error("Method not implemented.");
});
async invokeResource(form: MBusForm, content: Content): Promise<Content> {
throw new Error("Method not implemented.");
}

unlinkResource(form: MBusForm): Promise<void> {
return new Promise<void>((resolve, reject) => {
throw new Error("Method not implemented.");
});
async unlinkResource(form: MBusForm): Promise<void> {
throw new Error("Method not implemented.");
}

public subscribeResource(
public async subscribeResource(
form: MBusForm,
next: (value: Content) => void,
error?: (error: Error) => void,
complete?: () => void
): Promise<Subscription> {
return new Promise<Subscription>((resolve, reject) => {
throw new Error("Method not implemented.");
});
throw new Error("Method not implemented.");
}

async start(): Promise<void> {
Expand Down
4 changes: 1 addition & 3 deletions packages/binding-mbus/test/test-servient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ export default class DefaultServient extends Servient {
* start
*/
public start(): Promise<typeof WoT> {
return new Promise<typeof WoT>((resolve, reject) => {
return super.start();
});
return super.start();
}
}
4 changes: 1 addition & 3 deletions packages/binding-modbus/test/test-servient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ export default class DefaultServient extends Servient {
* start
*/
public start(): Promise<typeof WoT> {
return new Promise<typeof WoT>((resolve, reject) => {
return super.start();
});
return super.start();
}
}
11 changes: 4 additions & 7 deletions packages/binding-mqtt/src/mqtt-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,10 @@ export default class MqttClient implements ProtocolClient {
const requestUri = new url.URL(form.href);
const topic = requestUri.pathname.slice(1);

return new Promise<void>((resolve, reject) => {
if (this.client && this.client.connected) {
this.client.unsubscribe(topic);
debug(`MqttClient unsubscribed from topic '${topic}'`);
}
resolve();
});
if (this.client != null && this.client.connected) {
this.client.unsubscribe(topic);
debug(`MqttClient unsubscribed from topic '${topic}'`);
}
}

public async start(): Promise<void> {
Expand Down
Loading

0 comments on commit 4c3c203

Please sign in to comment.