Add typescript examples
authorChristopher Quadflieg <christopher.quadflieg@adsoul.com>
Fri, 2 Oct 2020 06:55:25 +0000 (08:55 +0200)
committerChristopher Quadflieg <christopher.quadflieg@adsoul.com>
Fri, 2 Oct 2020 06:55:25 +0000 (08:55 +0200)
examples/typescript/pool.ts [new file with mode: 0644]
examples/typescript/worker.ts [new file with mode: 0644]

diff --git a/examples/typescript/pool.ts b/examples/typescript/pool.ts
new file mode 100644 (file)
index 0000000..8e7d4bb
--- /dev/null
@@ -0,0 +1,22 @@
+import { join } from "path";
+import { DynamicThreadPool, FixedThreadPool } from "poolifier";
+import { MyData, MyResponse } from "./worker";
+
+export const fixedPool = new FixedThreadPool<MyData, Promise<MyResponse>>(
+  8,
+  join(__dirname, "worker.js"),
+  {
+    errorHandler: (e) => console.error(e),
+    onlineHandler: () => console.log("Worker is online"),
+  }
+);
+
+export const dynamicPool = new DynamicThreadPool<MyData, Promise<MyResponse>>(
+  2,
+  8,
+  join(__dirname, "worker.js"),
+  {
+    errorHandler: (e) => console.error(e),
+    onlineHandler: () => console.log("Worker is online"),
+  }
+);
diff --git a/examples/typescript/worker.ts b/examples/typescript/worker.ts
new file mode 100644 (file)
index 0000000..0b44e64
--- /dev/null
@@ -0,0 +1,29 @@
+import { ThreadWorker } from "poolifier";
+
+export interface MyData {
+  ok: number;
+}
+
+export interface MyResponse {
+  message: string;
+  data: MyData;
+}
+
+class MyThreadWorker extends ThreadWorker<MyData, Promise<MyResponse>> {
+  constructor() {
+    super((data) => this.process(data), {
+      maxInactiveTime: 60_000,
+      async: true,
+    });
+  }
+
+  private async process(data: MyData): Promise<MyResponse> {
+    return new Promise((resolve) => {
+      setTimeout(() => {
+        resolve({ message: "Hello from Worker :)", data });
+      }, 10_000);
+    });
+  }
+}
+
+export default new MyThreadWorker();