All Projects → borderless → context

borderless / context

Licence: MIT license
Tiny, type-safe, JavaScript-native `context` implementation

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to context

sanic-plugin-toolkit
Easily create Plugins for Sanic!
Stars: ✭ 49 (+172.22%)
Mutual labels:  context
reactube-client
A clone Youtube Web Player using React Provider Pattern, React Context and Typescript
Stars: ✭ 92 (+411.11%)
Mutual labels:  context
remote-lib
💫 Convert your JavaScript library to a remote service.
Stars: ✭ 40 (+122.22%)
Mutual labels:  context
mercadoabierto
The Mercadolibre clone
Stars: ✭ 24 (+33.33%)
Mutual labels:  context-api
sigctx
Go contexts for graceful shutdown
Stars: ✭ 55 (+205.56%)
Mutual labels:  context
les-chat
Real-time messenger with private, public & group chat. Made using PERN + GraphQL stack.
Stars: ✭ 48 (+166.67%)
Mutual labels:  context-api
laravel-react-spa
A Laravel-React SPA starter project template.
Stars: ✭ 94 (+422.22%)
Mutual labels:  context
ktx
简化Android开发的Kotlin库
Stars: ✭ 39 (+116.67%)
Mutual labels:  context
use-app-state
🌏 useAppState() hook. that global version of setState() built on Context.
Stars: ✭ 65 (+261.11%)
Mutual labels:  context
eval-estree-expression
Safely evaluate JavaScript (estree) expressions, sync and async.
Stars: ✭ 22 (+22.22%)
Mutual labels:  context
react-context-responsive
A package that provides a responsive context to your application, using React Context API.
Stars: ✭ 25 (+38.89%)
Mutual labels:  context-api
Google-Clone
A Google Clone which built with ReactJS. When you click Gmail button, you will be directed to my other project, Gmail Clone. You can search whatever you want and send realtime emails by clicking Gmail button!
Stars: ✭ 37 (+105.56%)
Mutual labels:  context-api
no-redux
⚛️ 🎣 Experimenting with using hooks and context instead of Redux
Stars: ✭ 79 (+338.89%)
Mutual labels:  context
retrygroup
Package retrygroup provides synchronization, Context cancelation for groups of retry goroutines working on subtasks of a common task.
Stars: ✭ 18 (+0%)
Mutual labels:  context
database
Simple and easy go database micro framework
Stars: ✭ 12 (-33.33%)
Mutual labels:  context
go-csync
Golang: contex-aware synchronization primitives (mutex).
Stars: ✭ 27 (+50%)
Mutual labels:  context
react-context-io
Share state with ease.
Stars: ✭ 22 (+22.22%)
Mutual labels:  context
hero
A superhero encyclopaedia made in React Native. Pulls from the SuperHeroAPI & ComicVine API
Stars: ✭ 53 (+194.44%)
Mutual labels:  context-api
use-global-hook
Painless global state management for React using Hooks and Context API in 1KB!
Stars: ✭ 54 (+200%)
Mutual labels:  context-api
pokehooks-labs
A laboratory to use pokemons and do some experiments with React Hooks API
Stars: ✭ 35 (+94.44%)
Mutual labels:  context-api

Context

NPM version NPM downloads Build status Test coverage Bundle size

Tiny, type-safe, JavaScript-native context implementation.

Why? Working on a project across browsers, workers and node.js requires different implementations on the same thing, e.g. fetch vs require('http'). Go's context package provides a nice abstraction to bring all the interfaces together. By implementing a JavaScript first variation, we can achieve the same benefits.

Installation

npm install @borderless/context --save

Usage

Context values are unidirectional.

import { background, withValue } from "@borderless/context";

// Extend the default `background` context with a value.
const ctx = withValue(background, "test", "test");

ctx.value("test"); //=> "test"
background.value("test"); // Invalid.

Abort

Use withAbort to support cancellation of execution in your application.

import { withAbort } from "@borderless/context";

const [ctx, abort] = withAbort(parentCtx);

onUserCancelsTask(() => abort(new Error("User canceled task")));

Timeout

Use withTimeout when you want to abort after a specific duration:

import { withTimeout } from "@borderless/context";

const [ctx, abort] = withTimeout(parentCtx, 5000); // You can still `abort` manually.

Using Abort

The useAbort method will return a Promise which rejects when aborted.

import { useAbort } from "@borderless/context";

// Race between the abort signal and making an ajax request.
Promise.race([useAbort(ctx), ajax("http://example.com")]);

Example

Abort Controller

Use context with other abort signals, such as fetch.

import { useAbort, Context } from "@borderless/context";

function request(ctx: Context<{}>, url: string) {
  const controller = new AbortController();
  withAbort(ctx).catch(e => controller.abort());
  return fetch(url, { signal: controller.signal });
}

Application Tracing

Distributed application tracing is a natural example for context:

import { Context, withValue } from "@borderless/context";

// Use a unique symbol for tracing.
const spanKey = Symbol("span");

// Start a new span, and automatically use "parent" span.
export function startSpan<T extends { [spanKey]?: Span }>(
  ctx: Context<T>,
  name: string
): [Span, Context<T & { [spanKey]: Span }>] {
  const span = tracer.startSpan(name, {
    childOf: ctx.value(spanKey)
  });

  return [span, withValue(ctx, spanKey, span)];
}

// server.js
export async function app(req, next) {
  const [span, ctx] = startSpan(req.ctx, "app");

  req.ctx = ctx;

  try {
    return await next();
  } finally {
    span.finish();
  }
}

// middleware.js
export async function middleware(req, next) {
  const [span, ctx] = startSpan(req.ctx, "middleware");

  req.ctx = ctx;

  try {
    return await next();
  } finally {
    span.finish();
  }
}

Libraries

JavaScript and TypeScript libraries can accept a typed context argument.

import { Context, withValue } from "@borderless/context";

export function withSentry<T>(ctx: Context<T>) {
  return withValue(ctx, sentryKey, someSentryImplementation);
}

export function captureException(
  ctx: Context<{ [sentryKey]: SomeSentryImplementation }>,
  error: Error
) {
  return ctx.value(sentryKey).captureException(error);
}

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].