How to use on-finished - 10 common examples

To help you get started, we’ve selected a few on-finished examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github graphile / postgraphile / src / createServer.js View on Github external
server.all(route, graphqlHTTP(async (req, res) => {
    // Acquire a new client for every request.
    const client = await pg.connectAsync(pgConfig)

    try {
      // Start a transaction for our client and set it up.
      await client.queryAsync('begin')

      // If we have a secret, let’s setup the request transaction.
      await setupRequestTransaction(req, client, secret, anonymousRole)

      // Make sure we release our client back to the pool once the response has
      // finished.
      onFinished(res, () => {
        // Try to end our session with a commit. If it succeeds, release the
        // client back into the pool. If it fails, release the client back into
        // the pool, but also report that it failed. We cannot report an error in
        // the request at this point because it has finished.
        client.queryAsync('commit')
          .then(() => client.end())
          .catch(error => {
            console.error(error.stack) // eslint-disable-line no-console
            client.end()
          })
      })

      return {
        // Await the `graphqlSchema` because it may be a promise.
        schema: await graphqlSchema,
        context: { client },
github strongloop / loopback-next / packages / rest / src / request-context.ts View on Github external
constructor(
    public readonly request: Request,
    public readonly response: Response,
    parent: Context,
    public readonly serverConfig: RestServerResolvedConfig,
    name?: string,
  ) {
    super(parent, name);
    this._setupBindings(request, response);
    onFinished(this.response, () => {
      // Close the request context when the http response is finished so that
      // it can be recycled by GC
      this.close();
    });
  }
github coralproject / talk / src / core / server / app / middleware / logging.ts View on Github external
export const accessLogger: RequestHandler = (req, res, next) => {
  const startTime = now();

  onFinished(res, () => {
    // Compute the end time.
    const responseTime = Math.round(now() - startTime);

    // Get some extra goodies from the request.
    const userAgent = req.get("User-Agent");

    // Grab the logger.
    const log = req.coral ? req.coral.logger : logger;

    // Log this out.
    log.debug(
      {
        url: req.originalUrl || req.url,
        method: req.method,
        statusCode: res.statusCode,
        host: req.hostname,
github ElementsProject / paypercall / src / paypercall.js View on Github external
return (amount, currency=defCurrency) => pwrap(async (req, res, next) => {
    const invid = req.get('X-Token') && parseToken(req)
        , inv   = invid && await charge.fetch(invid)
        , paid  = inv && inv.status === 'paid' && inv.paid_at > now() - accessExp

    if (paid) {
      if (!await markSpent(inv)) return res.status(410).send('Error: payment token already spent')

      onFinished(res, async _ => await markDone(inv, res))
      req.invoice = inv
      next()
    } else {
      const inv = await charge.invoice({
        amount, currency
      , metadata: { source: 'paypercall', req: only(req, 'method', 'path') }
      , description: `Pay to call ${req.method} ${req.path}`
      , expiry: invoiceExp
      })

      res.status(402) // Payment Required
         .type('application/vnd.lightning.bolt11')
         .set('X-Token', makeToken(req, inv.id))
         .send(inv.payreq)
    }
  })
github coralproject / talk / src / core / server / app / middleware / metrics.ts View on Github external
return (req, res, next) => {
    const startTime = now();

    onFinished(res, () => {
      // Compute the end time.
      const responseTime = Math.round(now() - startTime);

      // Increment the request counter.
      httpRequestsTotal.labels(`${res.statusCode}`, req.method).inc();

      // Only compute the request path when status code isn't 404 to avoid flood
      if (res.statusCode !== 404) {
        // Add the request duration.
        httpRequestDurationMilliseconds
          .labels(req.method, req.baseUrl + req.path)
          .observe(responseTime);
      }
    });
    next();
  };
github jfhbrook / node-ecstatic / lib / ecstatic.js View on Github external
function serve(stat) {
      if (onFinished.isFinished(res)) {
        return;
      }

      // Do a MIME lookup, fall back to octet-stream and handle gzip
      // and brotli special case.
      const defaultType = opts.contentType || 'application/octet-stream';

      let contentType = mime.getType(file, defaultType);
      let charSet;
      const range = (req.headers && req.headers.range);
      const lastModified = (new Date(stat.mtime)).toUTCString();
      const etag = generateEtag(stat, weakEtags);
      let cacheControl = cache;
      if (contentType) {
        charSet = mime.lookupCharset(contentType);
        if (charSet) {
github fontello / fontello / lib / autoload / hooks / responder / response_send.js View on Github external
N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
    var res = env.origin.res,
        headers = env.headers,
        body = env.body,
        statusCode;

    // If someone already sent reply - do nothing
    if (isFinished(res)) return;

    // That should not happen, because custom senders should wait
    // stream end.
    if (res.headerSent) return;

    //
    // Set some obligatory headers
    //

    headers.Server = headers.Server || 'Sansun Calakci';
    // added by node automatically
    // headers['Date'] = headers['Date'] || new Date).toUTCString();

    //
    // Remove Accept-Ranges if it wasn't explicitly set
    //
github nodeca / nodeca.core / lib / autoload / hooks / responder / response_send.js View on Github external
N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
    var res = env.origin.res,
        headers = env.headers,
        body = env.body,
        statusCode;

    // If someone already sent reply - do nothing
    if (isFinished(res)) return;

    // That should not happen, because custom senders should wait
    // stream end.
    if (res.headerSent) return;

    //
    // Set some obligatory headers
    //

    headers.Server = headers.Server || 'Sansun Calakci';
    // added by node automatically
    // headers['Date'] = headers['Date'] || new Date).toUTCString();

    //
    // Remove Accept-Ranges if it wasn't explicitly set
    //
github http-party / http-server / lib / ecstatic.js View on Github external
function serve(stat) {
      if (onFinished.isFinished(res)) {
        return;
      }

      // Do a MIME lookup, fall back to octet-stream and handle gzip
      // and brotli special case.
      const defaultType = opts.contentType || 'application/octet-stream';

      let contentType = mime.getType(file, defaultType);
      let charSet;
      const range = (req.headers && req.headers.range);
      const lastModified = (new Date(stat.mtime)).toUTCString();
      const etag = generateEtag(stat, weakEtags);
      let cacheControl = cache;
      if (contentType) {
        charSet = mime.lookupCharset(contentType);
        if (charSet) {
github fox1t / fastify-multer / test / fastify-integration.ts View on Github external
concat({ encoding: 'buffer' }, function(body) {
          onFinished(req, function() {
            cb(null, res, body)
          })
        }),
      )

on-finished

Execute a callback when a request closes, finishes, or errors

MIT
Latest version published 2 years ago

Package Health Score

70 / 100
Full package analysis

Popular on-finished functions

Similar packages