How to use once - 10 common examples

To help you get started, we’ve selected a few once 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 newrelic / newrelic-ruby-agent / .github / actions / build-ruby / node_modules / @octokit / request-error / dist-web / index.js View on Github external
import { Deprecation } from 'deprecation';
import once from 'once';

const logOnce = once((deprecation) => console.warn(deprecation));
/**
 * Error with extra properties to help with debugging
 */
class RequestError extends Error {
    constructor(message, statusCode, options) {
        super(message);
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
        this.name = "HttpError";
        this.status = statusCode;
        Object.defineProperty(this, "code", {
            get() {
                logOnce(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
github Azure / dev-spaces / actions / add-review-url / node_modules / @octokit / request-error / dist-src / index.js View on Github external
import { Deprecation } from "deprecation";
import once from "once";
const logOnce = once((deprecation) => console.warn(deprecation));
/**
 * Error with extra properties to help with debugging
 */
export class RequestError extends Error {
    constructor(message, statusCode, options) {
        super(message);
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
        this.name = "HttpError";
        this.status = statusCode;
        Object.defineProperty(this, "code", {
            get() {
                logOnce(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
github digidem / mapeo-desktop / src / renderer / create-zip.js View on Github external
const tasks = remoteFiles.map(({ url, metadataPath, ...options }) => cb => {
    cb = once(cb)
    const start = Date.now()
    console.log('Requesting', url)
    // I tried doing this by adding streams to the zipfile, but it's really hard
    // to catch errors when trying to download an image, so you end up with
    // corrupt files in the zip. This uses a bit more memory, but images are
    // only added once they have downloaded correctly
    ky.get(url)
      .arrayBuffer()
      .then(arrBuf => {
        console.log('Req end in ' + (Date.now() - start) + 'ms ' + metadataPath)
        zipfile.addBuffer(Buffer.from(arrBuf), metadataPath, {
          ...options,
          store: true
        })
        cb()
      })
github beakerbrowser / beaker / app / background-process / protocols / dat.js View on Github external
function datServer (req, res) {
  var cb = once((code, status) => { 
    res.writeHead(code, status, { 'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'unsafe-inline';" })
    res.end(errorPage(code + ' ' + status))
  })
  var queryParams = url.parse(req.url, true).query

  // check the nonce
  // (only want this process to access the server)
  if (queryParams.nonce != nonce)
    return cb(403, 'Forbidden')

  // validate request
  var urlp = url.parse(queryParams.url)
  if (!urlp.host)
    return cb(404, 'Archive Not Found')
  if (req.method != 'GET')
    return cb(405, 'Method Not Supported')
github beakerbrowser / beaker / app / background-process / protocols / fs.js View on Github external
function ipfsServer (req, res) {
  var cb = once((code, status) => {
    res.writeHead(code, status, {
      'Content-Type': 'text/html',
      'Content-Security-Policy': "default-src 'unsafe-inline';",
      'Access-Control-Allow-Origin': '*'
    })
    res.end(errorPage(code + ' ' + status))
  })
  function redirectToFolder () {
    // header-redirects crash electron (https://github.com/electron/electron/issues/6492)
    // use this instead, for now
    res.writeHead(200, 'OK', { 'Content-Type': 'text/html', 'Content-Security-Policy': IPFS_CSP })
    res.end('')    
  }
  var queryParams = url.parse(req.url, true).query

  // check the nonce
github beakerbrowser / beaker / app / bg / dat / protocol.js View on Github external
export const electronHandler = async function (request, respond) {
  // log warnings now, after the logger has setup its transports
  if (utpLoadError) {
    logger.warn('Failed to load utp-native. Peer-to-peer connectivity may be degraded.', {err: utpLoadError.toString()})
  }
  if (sodiumLoadError) {
    logger.warn('Failed to load sodium-native. Performance may be degraded.', {err: sodiumLoadError.toString()})
  }

  respond = once(respond)
  var respondError = (code, status, errorPageInfo) => {
    if (errorPageInfo) {
      errorPageInfo.validatedURL = request.url
      errorPageInfo.errorCode = code
    }
    var accept = request.headers.Accept || ''
    if (accept.includes('text/html')) {
      respond({
        statusCode: code,
        headers: {
          'Content-Type': 'text/html',
          'Content-Security-Policy': "default-src 'unsafe-inline' beaker:;",
          'Access-Control-Allow-Origin': '*'
        },
        data: intoStream(errorPage(errorPageInfo || (code + ' ' + status)))
      })
github streamr-dev / streamr-client-javascript / src / StreamrClient.js View on Github external
this.connection.on(UnicastMessage.TYPE, async (msg) => {
            const stream = this._getSubscribedStreamPartition(msg.streamMessage.getStreamId(), msg.streamMessage.getStreamPartition())
            if (stream) {
                const sub = this.resendUtil.getSubFromResendResponse(msg)

                if (sub && stream.getSubscription(sub.id)) {
                    // sub.handleResentMessage never rejects: on any error it emits an 'error' event on the Subscription
                    sub.handleResentMessage(
                        msg.streamMessage,
                        once(() => stream.verifyStreamMessage(msg.streamMessage)), // ensure verification occurs only once
                    )
                } else {
                    debug('WARN: request id not found for stream: %s, sub: %s', msg.streamMessage.getStreamId(), msg.requestId)
                }
            } else {
                debug('WARN: message received for stream with no subscriptions: %s', msg.streamMessage.getStreamId())
            }
        })
github shastajs / sutro / src / handleAsync.js View on Github external
const handleAsync = (fn, cb) => {
  // flat value
  if (typeof fn !== 'function') return cb(null, fn)

  const wrapped = once(cb)

  // call fn w callback
  let res
  try {
    res = fn(wrapped)
  } catch (err) {
    return wrapped(err)
  }

  // using a callback, itll call with a response
  if (typeof res === 'undefined') return

  // using a promise
  if (res != null && typeof res === 'object' && typeof res.then === 'function') {
    res.then((data) => {
      wrapped(null, data)
github DonutEspresso / big-json / lib / index.js View on Github external
function _stringify(opts, callback) {
    assert.object(opts, 'opts');
    assert.func(callback, 'callback');

    let stringified = '';
    const stringifyStream = createStringifyStream(opts);
    const passthroughStream = new stream.PassThrough();
    const cb = once(callback);

    // setup the passthrough stream as a sink
    passthroughStream.on('data', function(chunk) {
        stringified += chunk;
    });

    passthroughStream.on('end', function() {
        return cb(null, stringified);
    });

    // don't know what errors stringify stream may emit, but pass them back
    // up.
    stringifyStream.on('error', function(err) {
        return cb(err);
    });
github Yoctol / bottender / packages / bottender / src / console / __tests__ / ConsoleBot.spec.ts View on Github external
it('should print state when entering /state', async () => {
    const bot = new ConsoleBot();
    const handler = jest.fn();

    bot.onEvent(handler);

    readline.createInterface.mockReturnValue({
      once: once((string, fn) => fn('/state')),
      close: jest.fn(),
    });

    bot.createRuntime();

    await new Promise(process.nextTick);

    expect(process.stdout.write).toBeCalledWith('Bot > {}\n');
    expect(process.stdout.write).toBeCalledWith('You > ');
  });

once

Run a function exactly one time

ISC
Latest version published 7 years ago

Package Health Score

67 / 100
Full package analysis

Popular once functions