How to use @hapi/wreck - 10 common examples

To help you get started, we’ve selected a few @hapi/wreck 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 hapijs / ammo / test / index.js View on Github external
it('emits error on internal processing errors', async () => {

        const random = Buffer.alloc(5000);
        const source = Wreck.toReadableStream(random);
        const stream = new Ammo.Clip({ from: 1000, to: 4000 });

        stream._range = null;         // Force a processing error

        await expect(Wreck.read(source.pipe(stream))).to.reject(Error);
    });
github hapijs / b64 / test / index.js View on Github external
it('flushes remainder', async () => {

        const value = '0123456789';
        const encoded = B64.encode(Buffer.from(value));         // MDEyMzQ1Njc4OQ==

        const stream = new internals.Payload([encoded.slice(0, 14)]);
        const source = stream.pipe(new B64.Decoder());

        const payload = await Wreck.read(source);
        expect(payload.toString()).to.equal(value.toString());
    });
});
github hapijs / hapi / test / headers.js View on Github external
it('returns a normal response when JSONP requested but stream returned', async () => {

            const server = Hapi.server();
            const stream = Wreck.toReadableStream('test');
            stream.size = 4;                                    // Non function for coverage
            server.route({ method: 'GET', path: '/', options: { jsonp: 'callback', handler: () => stream } });

            const res = await server.inject('/?callback=me');
            expect(res.payload).to.equal('test');
        });
    });
github elastic / kibana / x-pack / legacy / plugins / code / server / distributed / multinode / non_code_node_adapter.ts View on Github external
async requestFn(baseUrl: string, path: string, payload: RequestPayload, originRequest: Request) {
    const opt = {
      baseUrl,
      payload: JSON.stringify(payload),
      // redirect all headers to CodeNode
      headers: { ...filterHeaders(originRequest), 'kbn-xsrf': 'kibana' },
    };
    const promise = Wreck.request('POST', path, opt);
    const res: http.IncomingMessage = await promise;
    this.log.debug(`sending RPC call to ${baseUrl}${path} ${res.statusCode}`);
    if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
      const buffer: Buffer = await Wreck.read(res, {});
      try {
        return JSON.parse(buffer.toString(), (key, value) => {
          return value && value.type === 'Buffer' ? Buffer.from(value.data) : value;
        });
      } catch (e) {
        this.log.error('parse json failed: ' + buffer.toString());
        throw Boom.boomify(e, { statusCode: 500 });
      }
    } else {
      this.log.error(
        `received ${res.statusCode} from ${baseUrl}/${path}, params was ${util.inspect(
          payload.params
github senecajs / seneca / lib / transport.js View on Github external
.then(function(res) {
          var seneca_reply = function(res) {
            // backwards compatibility with seneca-transport
            if (!res.meta$) {
              res.meta$ = {
                id: meta.id
              }
            }

            seneca.reply(internalize_reply(sending_instance, res))
          }

          var wreck_read = Wreck.read(res, spec.wreck.read)
          wreck_read
            .then(function(body) {
              var data = parseJSON(body)

              // JSON cannot handle arbitrary array properties
              if (Array.isArray(data.array$)) {
                var array_data = data.array$
                array_data.meta$ = data.meta$
                data = array_data
              }

              seneca_reply(data)
            })
            .catch(seneca_reply)
        })
        .catch(function(err) {
github elastic / kibana / x-pack / legacy / plugins / code / server / distributed / multinode / non_code_node_adapter.ts View on Github external
async requestFn(baseUrl: string, path: string, payload: RequestPayload, originRequest: Request) {
    const opt = {
      baseUrl,
      payload: JSON.stringify(payload),
      // redirect all headers to CodeNode
      headers: { ...filterHeaders(originRequest), 'kbn-xsrf': 'kibana' },
    };
    const promise = Wreck.request('POST', path, opt);
    const res: http.IncomingMessage = await promise;
    this.log.debug(`sending RPC call to ${baseUrl}${path} ${res.statusCode}`);
    if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
      const buffer: Buffer = await Wreck.read(res, {});
      try {
        return JSON.parse(buffer.toString(), (key, value) => {
          return value && value.type === 'Buffer' ? Buffer.from(value.data) : value;
        });
      } catch (e) {
        this.log.error('parse json failed: ' + buffer.toString());
        throw Boom.boomify(e, { statusCode: 500 });
      }
    } else {
      this.log.error(
        `received ${res.statusCode} from ${baseUrl}/${path}, params was ${util.inspect(
          payload.params
        )}`
      );
      const body: Boom.Payload = await Wreck.read(res, { json: true });
      throw new Boom(body.message, { statusCode: res.statusCode || 500, data: body.error });
github hapijs / bell / lib / oauth.js View on Github external
if (!settings.provider.useParamsAuth) {
            requestOptions.headers.Authorization = 'Basic ' + (Buffer.from(settings.clientId + ':' + settings.clientSecret, 'utf8')).toString('base64');
        }

        if (settings.provider.headers) {
            Hoek.merge(requestOptions.headers, settings.provider.headers);
        }

        if (typeof settings.clientSecret === 'object') {
            Hoek.merge(requestOptions, settings.clientSecret);
        }

        // Obtain token

        try {
            var { res: tokenRes, payload } = await Wreck.post(settings.provider.token, requestOptions);
        }
        catch (err) {
            return h.unauthenticated(Boom.internal('Failed obtaining ' + name + ' access token', err), { credentials });
        }

        if (tokenRes.statusCode < 200 ||
            tokenRes.statusCode > 299) {

            return h.unauthenticated(Boom.internal('Failed obtaining ' + name + ' access token', payload), { credentials });
        }

        try {
            payload = internals.parse(payload);
        }
        catch (err) {
            Bounce.rethrow(err, 'system');
github hapijs / h2o2 / lib / index.js View on Github external
const Https = require('https');

const Hoek = require('@hapi/hoek');
const Joi = require('@hapi/joi');
const Wreck = require('@hapi/wreck');


const internals = {
    NS_PER_SEC: 1e9
};


internals.defaults = {
    httpClient: {
        request: Wreck.request.bind(Wreck),
        parseCacheControl: Wreck.parseCacheControl.bind(Wreck)
    },
    xforward: false,
    passThrough: false,
    redirects: false,
    timeout: 1000 * 60 * 3, // Timeout request after 3 minutes
    localStatePassThrough: false,   // Pass cookies defined by the server upstream
    maxSockets: Infinity,
    downstreamResponseTime: false
};


internals.schema = Joi.object({
    httpClient: Joi.object({
        request: Joi.func(),
        parseCacheControl: Joi.func()
    }),
github hapijs / hapi / test / request.js View on Github external
it('returns not found on internal only route (external)', async () => {

            const server = Hapi.server();
            server.route({
                method: 'GET',
                path: '/some/route',
                options: {
                    isInternal: true,
                    handler: () => 'ok'
                }
            });

            await server.start();
            const err = await expect(Wreck.get('http://localhost:' + server.info.port)).to.reject();
            expect(err.data.res.statusCode).to.equal(404);
            expect(err.data.payload.toString()).to.equal('{"statusCode":404,"error":"Not Found","message":"Not Found"}');
            await server.stop();
        });
github hapijs / hapi / test / core.js View on Github external
it('uses a provided listener with manual listen', async () => {

        const listener = Http.createServer();
        const server = Hapi.server({ listener, autoListen: false });
        server.route({ method: 'GET', path: '/', handler: () => 'ok' });

        const listen = () => {

            return new Promise((resolve) => listener.listen(0, 'localhost', resolve));
        };

        await listen();
        await server.start();
        const { payload } = await Wreck.get('http://localhost:' + server.info.port + '/');
        expect(payload.toString()).to.equal('ok');
        await server.stop();
    });

@hapi/wreck

HTTP Client Utilities

BSD-3-Clause
Latest version published 11 days ago

Package Health Score

89 / 100
Full package analysis