1.0.1 • Published 5 years ago

swork-if v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

swork-if

npm travis ci coverage download Greenkeeper badgeJoin the chat at https://gitter.im/swork-chat/community

swork-if is a swork middleware designed to create logical paths conditional upon the incoming request. This allows for incremental branching strategies to reduce redundant conditional checks and overall simplified middleware. It is built with TypeScript and async methods.

License

MIT

Installation

npm install swork-if

yarn add swork-if

Example

// sw.ts
import { Swork } from "swork";
import "swork-if";
import { buildApiSwork } from "./apiSwork";
import { buildNotApiSwork } from "./notApiSwork";

// Define root app
export const app = new Swork();

// Use api swork app if condition is met
app.useIf((context: FetchContext) => {
    return context.request.headers.get("Accept") === "application/json";
}, buildApiSwork());

// Else
app.use(buildNotApiSwork());

app.listen();

In the above example, the service worker conditionally re-routes the logic flow to the api swork app whenever the condition is true. Whenever the condition is false, the logic passes over the api logic flow and onto the next middleware.

Methods

useIf

useIf(predicate: (context: FetchContext) => Promise<boolean> | boolean, app: Swork): Swork

Create a conditional branch in the app workflow. If predicate returns true the provided swork app will execute. If predicate returns false, the provided swork app is ignored and execution continues.

Notes

useIf can be used by nested swork applications and is encouraged when deep branching strategies are required.

Contact

If you are using swork or any of its related middlewares, please let me know on gitter. I am always looking for feedback or additional middleware ideas.