express#$Response JavaScript Examples

The following examples show how to use express#$Response. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: Actions.js    From mox with MIT License 5 votes vote down vote up
res(fn: (res: $Response) => void): Actions {
    this._addResTransform((body, ctx) => {
      fn(ctx.res);
      return body;
    });
    return this;
  }
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: base-transformers.js    From mox with MIT License 5 votes vote down vote up
Promise<$Response> {
    const resOrPromise = this.modify(body, context);
    return new Promise(resolve => {
      Promise.resolve(resOrPromise).then(resolve);
    });
  }
Example #13
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 #14
Source File: proxy-request.js    From mox with MIT License 5 votes vote down vote up
sendToClient = (body: any, res: $Response) => {
  res.removeHeader('transfer-encoding');
  if (typeof body === 'object' && body != null) {
    res.json(body);
  } else {
    res.send(body);
  }
}