Skip to content

Instantly share code, notes, and snippets.

@Artaud
Last active February 27, 2021 05:46
Show Gist options
  • Save Artaud/a1cb76c32d76e68f09b57b6b94d5badf to your computer and use it in GitHub Desktop.
Save Artaud/a1cb76c32d76e68f09b57b6b94d5badf to your computer and use it in GitHub Desktop.
Worker threads in FeathersJS
import {Id, NullableId, Paginated, Params, ServiceMethods, SetupMethod} from '@feathersjs/feathers';
import {App} from '../../app.interface'
import {isWorkerRuntime, Pool, spawn, Thread, Worker} from "threads";
import {JobWorker} from "./jobWorker";
interface ServiceOptions {}
export class Jobs implements ServiceMethods<Data>, SetupMethod {
app: App;
options: ServiceOptions;
workerPool: Pool<JobWorker & Thread> | undefined
constructor (options: ServiceOptions = {}, app: App) {
this.options = options;
this.app = app;
}
setup(app: App, path: string): void {
if (!isWorkerRuntime()) {
// Creates threadPool at start of the app, but doesn't recreate it when a worker is importing App and setting up services for his own use
this.workerPool = Pool<JobWorker & Thread>(() => spawn<JobWorker>(new Worker("./jobWorker")), 8)
}
}
async create (data: Data, params?: Params): Promise<Data> {
const testTask = this.workerPool?.queue(jobWorker => jobWorker.doMyJob())
testTask?.then(() => {
// do something after the job finishes
})
return data;
}
}
import { expose } from "threads/worker"
import app from '../../app'
const jobWorker = {
async doMyJob() {
const reports: Report[] = await app.service('reports').create()
}
}
app.setup()
export type JobWorker = typeof jobWorker
expose(jobWorker)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment