https://github.com/egoist/typed-worker
Type-safe and Promisified API for Web Worker and Iframe
https://github.com/egoist/typed-worker
Last synced: 7 months ago
JSON representation
Type-safe and Promisified API for Web Worker and Iframe
- Host: GitHub
- URL: https://github.com/egoist/typed-worker
- Owner: egoist
- License: mit
- Created: 2022-08-13T17:00:20.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2024-01-17T15:20:14.000Z (over 1 year ago)
- Last Synced: 2024-12-09T18:13:02.258Z (7 months ago)
- Language: TypeScript
- Homepage:
- Size: 34.2 KB
- Stars: 194
- Watchers: 2
- Forks: 5
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
**💛 You can help the author become a full-time open-source maintainer by [sponsoring him on GitHub](https://github.com/sponsors/egoist).**
---
# typed-worker
[](https://npm.im/typed-worker) [](https://npm.im/typed-worker) [](https://paka.dev/npm/typed-worker)
## Install
```bash
npm i typed-worker
```## Usage
Create a `worker.ts`:
```ts
import { handleActions } from "typed-worker"export const actions = {
async sum(a: number, b: number) {
await someHeavyOperation()
return a + b
},
}export type Actions = typeof actions
handleActions(actions)
```In your `app.ts` where you want to use the worker:
```ts
import { createWorker } from "typed-worker"
import { type Actions } from "./worker"const worker = createWorker(
// Require a bundler like Vite, webpack etc
() =>
new Worker(new URL("./worker.ts", import.meta.url), {
type: "module",
}),
)const result = await worker.run("sum", 1, 2)
expect(result).toBe(3)
```To use the `worker.ts` in an iframe instead of a web worker, you only need to return the `iframe` element in `createWorker` instead:
```ts
const iframe = createWorker(
() => document.querySelector("#your-iframe-element")!,
)const result = await iframe.run("sum", 1, 2)
```### Error handling
Errors thrown in the worker will be re-thrown when you call the `.run` method:
```ts
worker.run("some-problematic-action").catch((err) => {
// err is the error thrown in the worker
})
```## Sponsors
[](https://github.com/sponsors/egoist)
## License
MIT © [EGOIST](https://github.com/sponsors/egoist)