express#$Request JavaScript Examples

The following examples show how to use express#$Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js    From mox with MIT License 7 votes vote down vote up
logger = {
  log: (req: $Request, ...message: any[]) => {
    // eslint-disable-next-line no-console
    console.log(req.method, req.originalUrl, ...message);
  },
  error: (req: $Request, ...message: any[]) => {
    // eslint-disable-next-line no-console
    console.error('ERR', req.method, req.originalUrl, ...message);
  },
  warn: (req: $Request, ...message: any[]) => {
    // eslint-disable-next-line no-console
    console.warn(req.method, req.originalUrl, ...message);
  },
}
Example #2
Source File: Actions.js    From mox with MIT License 6 votes vote down vote up
apply(
    fn: (arg: { mox: ActionsI, req: $Request, res: $Response }) => void | Promise<void>
  ): Actions {
    const execute = async (passThrough: any, ctx: Context) => {
      const mox = new Actions(this.options);
      const { req, res } = ctx;
      await fn({ mox, req, res });
      ctx.transformStack.unshift(...mox._transformers);
      return passThrough;
    };
    this._transformers.push({
      triggerSend: false,
      modifyReq: execute,
      modifyRes: execute,
    });
    return this;
  }
Example #3
Source File: utils.js    From mox with MIT License 6 votes vote down vote up
normalizeReqHeaders = (req: $Request): void => {
  const headers = req.headers;
  const newHeaders = Object.keys(headers).reduce((accum: { [string]: any }, key) => {
    accum[key.toLowerCase()] = headers[key];
    return accum;
  }, {});
  req.headers = newHeaders;
}
Example #4
Source File: proxy-request.js    From mox with MIT License 6 votes vote down vote up
manualProxy = async (targetUrl: string, req: $Request): Promise<ManualProxyInfo> => {
  const requestBody = await defaultBodyHandler.serializeRequestBody(req);
  const details = pick(
    req,
    'httpVersion',
    'httpVersionMajor',
    'httpVersionMinor',
    'method',
    'url',
    'headers'
  );
  const gzip = details.headers?.['accept-encoding'] ? true : false;
  const opts = {
    ...details,
    headers: {
      ...details.headers,
      host: undefined,
      ...(requestBody != null ? { 'content-length': requestBody.length } : {}),
    },
    body: requestBody,
    method: details.method,
    gzip,
    url: targetUrl + req.url,
  };
  const proxyResponse = await new Promise<ManualProxyInfo>((resolve, reject) => {
    request(opts, (error, response, body) => {
      if (error) {
        reject(error);
      } else {
        resolve({ body, response });
      }
    });
  });
  return proxyResponse;
}
Example #5
Source File: proxy-request.js    From mox with MIT License 6 votes vote down vote up
processProxyResponse = async (
  proxyResponse: ManualProxyInfo,
  req: $Request,
  res: $Response
): any => {
  const body = await (defaultBodyHandler: BodyHandler).parseInterceptedResponseBody(
    proxyResponse.body,
    proxyResponse.response
  );
  if (proxyResponse.response.headers != null) {
    res.set(
      omit(
        proxyResponse.response.headers,
        'Content-Length',
        'content-length',
        'content-encoding',
        'Content-Encoding'
      )
    );
  }
  res.status(proxyResponse.response.statusCode);
  return body;
}
Example #6
Source File: mox-test-server.js    From mox with MIT License 6 votes vote down vote up
app.post('/*/send-back-text-body', async (req: $Request, res: $Response) => {
      const contentType = req.get('content-type');
      if (contentType !== 'text/plain') {
        res.status(400);
        res.send('Incorrect content type');
      } else {
        await new Promise(resolve => bodyParser.text()(req, null, resolve));
        res.type('text/plain');
        res.send(`received: ${String(req.body)}`);
      }
    });
Example #7
Source File: mox-test-server.js    From mox with MIT License 6 votes vote down vote up
app.post('/*/send-back-json-body', async (req: $Request, res: $Response) => {
      const contentType = req.get('content-type');
      if (contentType !== 'application/json') {
        res.status(400);
        res.send('Incorrect content type');
      } else {
        await new Promise(resolve => bodyParser.json()(req, null, resolve));
        res.type('application/json');
        res.send({ message: 'ok', received: req.body });
      }
    });
Example #8
Source File: mox-test-server.js    From mox with MIT License 6 votes vote down vote up
app.post('/*/first-5-chars', async (req: $Request, res: $Response) => {
      const contentType = req.get('content-type');
      if (contentType !== 'text/plain') {
        res.status(400);
        res.send('Incorrect content type');
      } else {
        await new Promise(resolve => bodyParser.text()(req, null, resolve));
        res.type('text/plain');
        res.send((req.body: any).substring(0, 5));
Example #9
Source File: MoxRouter.js    From mox with MIT License 6 votes vote down vote up
_applyMox(path: string, expressMethod: (path: string, handler: Handler) => any): Actions {
    const actions = new Actions(this._options);
    const compileOnce = once(() => actions.compile());
    expressMethod.call(this._options.app, path, (req: $Request, res: $Response, next) => {
      const handler = compileOnce();
      handler(req, res, next);
    });

    return actions;
  }
Example #10
Source File: DefaultBodyHandler.js    From mox with MIT License 6 votes vote down vote up
validRequestBody = (req: $Request) => {
  if (req.method === 'GET' || req.method === 'HEAD') {
    return (
      req.body != null &&
      typeof req.body === 'object' &&
      (Array.isArray(req.body) || Object.keys(req.body).length > 0)
    );
  } else {
    return req.body != null;
  }
}
Example #11
Source File: DefaultBodyHandler.js    From mox with MIT License 6 votes vote down vote up
restreamInitialRequestBody(req: $Request): * {
    if (validRequestBody(req)) {
      const content: string =
        typeof req.body === 'string' ? req.body : JSON.stringify(req.body) ?? '';
      if (req.get('content-length') !== String(content.length)) {
        req.headers['content-length'] = String(content.length);
      }
      return streamify([content]);
    }
  }
Example #12
Source File: DefaultBodyHandler.js    From mox with MIT License 6 votes vote down vote up
async parseInitialRequestBody(req: $Request): Promise<void> {
    if (req.is('application/json')) {
      return await new Promise(resolve => bodyParser.json()(req, null, resolve));
    } else if (req.is('text/*')) {
      return await new Promise(resolve => bodyParser.text()(req, null, resolve));
    } else {
      logger.warn(
        req,
        `WARNING: skipping parsing for content-type "${String(req.get('content-type'))}"`
      );
    }
  }
Example #13
Source File: Actions.js    From mox with MIT License 6 votes vote down vote up
/*
   * Request transforms
   * These transformations can only operate on the request. Primarily used to change the url of the request.
   */

  goto(path: string | ((from: string, req: $Request) => string)): Actions {
    this._addReqTransform((req: $Request) => {
      const toPath = typeof path === 'function' ? path(req.url, req) : path;
      req.url = toPath;
      return req;
    });
    return this;
  }
Example #14
Source File: Actions.js    From mox with MIT License 6 votes vote down vote up
log(opts: { hideHeaders: boolean } = {}): Actions {
    const { hideHeaders = false } = opts;
    this._transformers.push({
      triggerSend: false,
      modifyReq: (req: $Request) => {
        return new Promise(resolve => {
          logger.log(req, '\nREQUEST INFO:\n', {
            url: req.url,
            ...(hideHeaders ? {} : { headers: req.headers }),
            params: req.params,
            query: req.query,
          });
          resolve(req);
        });
      },
      modifyRes: (body, context: Context) => {
        return new Promise(resolve => {
          logger.log(context.req, '\nBODY:\n', body, '\nRESPONSE INFO:\n', {
            status: context.res.statusCode,
            // $FlowExpectError
            ...(hideHeaders ? {} : { headers: context.res.getHeaders() }),
          });
          resolve(body);
        });
      },
    });
    return this;
  }
Example #15
Source File: DefaultBodyHandler.js    From mox with MIT License 5 votes vote down vote up
serializeRequestBody(req: $Request): ?string {
    const useBody = validRequestBody(req);
    if (!useBody) {
      return undefined;
    }
    return typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
  }
Example #16
Source File: MoxServer.js    From mox with MIT License 5 votes vote down vote up
async start(initialize?: Initializer): * {
    if (typeof initialize === 'function') {
      initialize(this.getRouter());
    }

    this._apiProxy.on('error', err => {
      rawLogger.error('An error occurred in http proxy', err);
    });

    if (this.proxyUnmatchedRoutes === true) {
      this.app.all('/*', (req: $Request, res: $Response) => {
        this._apiProxy.web(req, res, { target: this.targetUrl });
      });
    }

    if (this.disableEtag === true) {
      this.app.disable('etag'); // prevent 304 not modified on proxy through
    }

    // eslint-disable-next-line node/no-deprecated-api
    const parsedUrl = url.parse(this.targetUrl);
    const isHttps = parsedUrl.protocol === 'https:';

    let server;
    if (isHttps) {
      const keys = await new Promise((resolve, reject) =>
        pem.createCertificate({ days: 30, selfSigned: true }, (err, keys) => {
          if (err) {
            reject(err);
          }
          resolve(keys);
        })
      );

      server = https.createServer(
        {
          key: keys.serviceKey,
          cert: keys.certificate,
        },
        (this.app: any)
      );
    } else {
      server = http.createServer(this.app);
    }

    server.on('upgrade', (req, socket, head) => {
      this._apiProxy.ws(req, socket, head, { target: this.targetUrl });
    });

    await new Promise((resolve, reject) => {
      server.listen(this.listenPort, e => {
        if (e != null) {
          return reject(e);
        }
        rawLogger.log(
          `Server is listening at ${isHttps ? 'https' : 'http'}://0.0.0.0:${this.listenPort}`
        );
        return resolve();
      });
    });

    return server;
  }
Example #17
Source File: mox-test-server.js    From mox with MIT License 5 votes vote down vote up
initTestServer = (
  port: number = 3100,
  name: string = 'default_server'
): Promise<http.Server> => {
  return new Promise<http.Server>(resolve => {
    const app: $Application<> = express();

    app.get('/*/array', (req: $Request, res: $Response) => {
      res.send(['foo', 'bar', 'baz']);
    });

    app.get('/*/object', (req: $Request, res: $Response) => {
      res.send({
        id: 'zxcv',
        name: 'Bob',
        location: 'Palo Alto, CA',
      });
    });

    app.get('/*/country/*/state/*/info', (req: $Request, res: $Response) => {
      const [, country, state] =
        req.originalUrl.match(/country\/([^/]+)\/state\/([^/]+)\/info/) ?? [];

      res.send({
        country,
        state,
      });
    });

    app.get('/*/info', (req: $Request, res: $Response) => {
      res.send({ name, port });
    });

    app.get('/*/send-back-header/:value', (req: $Request, res: $Response) => {
      const incHeader = req.header('x-mox-incoming-test');
      res.setHeader('x-mox-outgoing-test', req.params.value);
      res.send({ received: incHeader ?? null });
    });

    app.get('/*/text-plain-looks-like-json', (req: $Request, res: $Response) => {
      res.type('text/plain').send(JSON.stringify({ message: 'looks like json' }));
    });

    app.post('/*/send-back-foo', async (req: $Request, res: $Response) => {
      const contentType = req.get('content-type');
      if (contentType !== 'application/json') {
        res.status(400);
        res.send('Incorrect content type');
      } else {
        await new Promise(resolve => bodyParser.json()(req, null, resolve));
        res.type('application/json');
        res.send({ 'this-is-foo': (req.body: any).foo });
      }
    }
Example #18
Source File: Actions.js    From mox with MIT License 5 votes vote down vote up
compile(): Handler {
    this._transformers.push(new BaseTransformer({ triggerSend: true, fullPassThrough: true })); // ensure query gets sent if only req modifiers exist

    const handler = (originalReq: $Request, res: $Response) => {
      let req = originalReq;
      let triggered = false;
      let body;
      const context = {
        req,
        res,
        targetUrl: this.options.targetUrl,
        transformStack: [...this._transformers],
      };
      const execute = async () => {
        await defaultBodyHandler.parseInitialRequestBody(context.req);
        normalizeReqHeaders(req);
        while (context.transformStack.length !== 0) {
          const transformer = context.transformStack.shift();
          if (transformer.triggerSend && triggered === false) {
            triggered = true;
            if (transformer.fullPassThrough === true) {
              logger.log(req, 'Pass-through to', req.url);
              this.options.proxy(req, res, context.targetUrl);
              return;
            } else if (transformer.dontRequest === true) {
              logger.log(req, 'No request sent');
              body = {};
            } else {
              body = await proxyRequest(context.targetUrl, req, res);
            }
          }
          if (triggered) {
            body = await transformer.modifyRes(body, context);
          } else {
            req = await transformer.modifyReq(req, context);
            context.req = req;
          }
        }
        sendToClient(body, res);
      };
      execute().catch(err => {
        logger.error(req, `An unexpected error occurred ${err}`);
      });
    };
    return handler;
  }
Example #19
Source File: Actions.js    From mox with MIT License 5 votes vote down vote up
setBase(targetUrl: string): Actions {
    this._addReqTransform((req: $Request, context: Context) => {
      context.targetUrl = targetUrl;
      return req;
    });
    return this;
  }
Example #20
Source File: base-transformers.js    From mox with MIT License 5 votes vote down vote up
modifyReq(req: $Request, context: Ctx): Promise<$Request> {
    const reqOrPromise = this.modify(req, context);
    return new Promise(resolve => {
      Promise.resolve(reqOrPromise).then(resolve);
    });
  }
Example #21
Source File: base-transformers.js    From mox with MIT License 5 votes vote down vote up
(req: $Request, context: Ctx) => Promise<$Request>;
Example #22
Source File: base-transformers.js    From mox with MIT License 5 votes vote down vote up
// default pass through modifiers
  // eslint-disable-next-line no-unused-vars
  modifyReq(req: $Request, context: Ctx)
Example #23
Source File: base-transformers.js    From mox with MIT License 5 votes vote down vote up
Promise<$Request> {
    return new Promise(resolve => resolve(req));
  }
Example #24
Source File: Actions.js    From mox with MIT License 5 votes vote down vote up
mutate(mutator: (response: any, context: { req: $Request, res: $Response }) => any): Actions {
    this._addResTransform((body, { req, res }: Context) => mutator(body, { req, res }));
    return this;
  }
Example #25
Source File: proxy-request.js    From mox with MIT License 5 votes vote down vote up
proxyRequest = async (targetUrl: string, req: $Request, res: $Response): Promise<*> => {
  const proxyResponse = await manualProxy(targetUrl, req);
  logger.log(req, 'sent to', req.url);
  return await processProxyResponse(proxyResponse, req, res);
}
Example #26
Source File: Actions.js    From mox with MIT License 5 votes vote down vote up
req(fn: (req: $Request) => void): Actions {
    this._addReqTransform(req => {
      fn(req);
      return req;
    });
    return this;
  }