1.2.0 • Published 7 years ago

@ctx/context v1.2.0

Weekly downloads
2
License
MIT
Repository
-
Last release
7 years ago

Context

Build Status Dependency Status

Go's context package, reimplemented in Typescript. Carry timeouts, cancellations and arbitrary values through the entirety of your stack.

Installation

yarn add @ctx/context

Usage

This module defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes.

Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.

The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires.

Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:

Do not store Contexts inside classes and objects; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:

function DoSomething(ctx: context.Context, arg: any) {
	// ... use ctx ...
}

Do not pass an undefined Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

See https://blog.golang.org/context for example code for a server that uses Contexts.

Examples

Creating a context from an incoming request, and setting a timeout

This example is implemented by @ctx/express

const app = express()
app.use((req, res, next) => {
    // Set up a context
    if (!req.ctx) {
        req.ctx = context.Backgrond()
    }
    // Add a request id, or pass through an existing request id
    if (!req.ctx.Value('request-id')) {
        let cancel
        [req.ctx, cancel] = context.WithValue(req.ctx, 'request-id', new uuid())
        res.on('finish', () => cancel)
    }
    // Set a timeout for the request
    let cancel
    [req.ctx, cancel] = context.WithTimeout(req.ctx, 1000)
    res.on('finish', () => cancel)

    next()
})