Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/egoist/typed-worker
Type-safe and Promisified API for Web Worker and Iframe
https://github.com/egoist/typed-worker
Last synced: 3 days 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 (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-01-17T15:20:14.000Z (10 months ago)
- Last Synced: 2024-10-23T01:12:59.934Z (12 days 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
[![npm version](https://badgen.net/npm/v/typed-worker)](https://npm.im/typed-worker) [![npm downloads](https://badgen.net/npm/dm/typed-worker)](https://npm.im/typed-worker) [![paka type docs](https://badgen.net/badge/typedoc/typed-worker/pink)](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
[![sponsors](https://sponsors-images.egoist.dev/sponsors.svg)](https://github.com/sponsors/egoist)
## License
MIT © [EGOIST](https://github.com/sponsors/egoist)