express#RequestHandler TypeScript Examples

The following examples show how to use express#RequestHandler. 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: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 9 votes vote down vote up
export function mapClass(cls: ClassConstructor<object>): RequestHandler {
    return async (req: Request, res: Response, next: NextFunction) => {
        // Map to class
        let obj: object = plainToInstance(cls, req.body);

        // Validate class
        let errors = await validate(obj, {
            skipMissingProperties: true,
            whitelist: true,
            forbidNonWhitelisted: false,
            forbidUnknownValues: true,
        });
        if (errors.length > 0) {
            res.status(400).send({ error: true, errors: formatValidationErrors(errors) });
            return;
        }

        // Set validated class to locals
        res.locals.input = obj;
        next();
    };
}
Example #2
Source File: utils.ts    From big-web-quiz with Apache License 2.0 8 votes vote down vote up
export function requireSameOrigin(): RequestHandler {
  return (req, res, next) => {
    const reqOrigin = req.headers['origin'];

    if (reqOrigin !== origin) {
      res.status(403).json({ err: 'Request must be same origin' });
      return;
    }

    next();
  };
}
Example #3
Source File: api-utils.ts    From monkeytype with GNU General Public License v3.0 7 votes vote down vote up
/**
 * This utility checks that the server's configuration matches
 * the criteria.
 */
function validateConfiguration(
  options: ValidationOptions<MonkeyTypes.Configuration>
): RequestHandler {
  const {
    criteria,
    invalidMessage = "This service is currently unavailable.",
  } = options;

  return (req: MonkeyTypes.Request, _res: Response, next: NextFunction) => {
    const configuration = req.ctx.configuration;

    const validated = criteria(configuration);
    if (!validated) {
      throw new MonkeyError(503, invalidMessage);
    }

    next();
  };
}
Example #4
Source File: index.tsx    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
export function maybeRequireLogin(): RequestHandler {
  return (req, res, next) => {
    if (!requirePlayerLogin || req.session!.user) {
      next();
      return;
    }

    const error = 'Login required';
    res.status(403).send(error);
  };
}
Example #5
Source File: check-auth.ts    From Discord-Bot-TypeScript-Template with MIT License 6 votes vote down vote up
export function checkAuth(token: string): RequestHandler {
    return (req, res, next) => {
        if (req.headers.authorization !== token) {
            res.sendStatus(401);
            return;
        }
        next();
    };
}
Example #6
Source File: errorHandler.ts    From paystring with Apache License 2.0 6 votes vote down vote up
/**
 * A function used to wrap asynchronous Express middlewares.
 * It catches async errors so Express can pass them to an error handling middleware.
 *
 * @param handler - An Express middleware function.
 *
 * @returns An Express middleware capable of catching asynchronous errors.
 */
export function wrapAsync(handler: RequestHandler): RequestHandler {
  return async (
    req: Request,
    res: Response,
    next: NextFunction,
  ): Promise<void> => Promise.resolve(handler(req, res, next)).catch(next)
}
Example #7
Source File: server.ts    From express-zod-api with MIT License 6 votes vote down vote up
createNotFoundHandler =
  (errorHandler: AnyResultHandler, logger: Logger): RequestHandler =>
  (request, response) => {
    const error = createHttpError(
      404,
      `Can not ${request.method} ${request.path}`
    );
    try {
      errorHandler.handler({
        request,
        response,
        logger,
        error,
        input: null,
        output: null,
      });
    } catch (e) {
      if (e instanceof Error) {
        lastResortHandler({
          response,
          logger,
          error: new ResultHandlerError(e.message, error),
        });
      }
    }
  }
Example #8
Source File: Request.ts    From hypixel-skyblock-facade with MIT License 6 votes vote down vote up
/**
 * Runs an async function and catches the errors thrown in it
 * and returns them to the Express error handler.
 *
 * @param fn The function that should be handled asynchronously
 */
export function asyncWrap(fn: RequestHandler) {
  return (request: Request, response: Response, next: NextFunction) => {
    return Promise.resolve(fn(request, response, next)).catch(next)
  }
}
Example #9
Source File: metrics.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a /metrics endpoint, register default runtime metrics and instrument the router.
 */
export function metricsHandler(): RequestHandler {
  // We can only initialize the metrics once and have to clean them up between hot reloads
  useHotCleanup(module, () => prom.register.clear());

  return promBundle({
    includeMethod: true,
    includePath: true,
    // Using includePath alone is problematic, as it will include path labels with high
    // cardinality (e.g. path params). Instead we would have to template them. However, this
    // is difficult, as every backend plugin might use different routes. Instead we only take
    // the first directory of the path, to have at least an idea how each plugin performs:
    normalizePath,
    promClient: { collectDefaultMetrics: {} },
  });
}
Example #10
Source File: guards.ts    From project-loved-web with MIT License 6 votes vote down vote up
function hasRoleMiddleware(roleIds: readonly Role[], errorMessage: string): RequestHandler {
  return function (request, response, next) {
    const user = response.typedLocals.user as UserWithRoles | undefined;

    if (user == null) {
      return response.status(401).json({ error: errorMessage });
    }

    if (!isAdmin(user, request.method) && !hasRole(user, roleIds)) {
      return response.status(403).json({ error: errorMessage });
    }

    next();
  };
}
Example #11
Source File: adapter.ts    From farrow with MIT License 6 votes vote down vote up
adapter = (httpPipeline: HttpPipeline): RequestHandler => {
  return (req, res, next) => {
    return httpPipeline.handle(req, res, {
      onLast: () => {
        next()
      },
    })
  }
}
Example #12
Source File: cache-controller.ts    From stacks-blockchain-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check if the request has an up-to-date cached response by comparing the `If-None-Match` request header to the
 * current state. If the cache is valid then a `304 Not Modified` response is sent and the route handling for
 * this request is completed. If the cache is outdated, the current state is added to the `Request.locals` for
 * later use in setting response cache headers.
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#freshness
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match
 * ```md
 * The If-None-Match HTTP request header makes the request conditional. For GET and HEAD methods, the server
 * will return the requested resource, with a 200 status, only if it doesn't have an ETag matching the given
 * ones. For other methods, the request will be processed only if the eventually existing resource's ETag
 * doesn't match any of the values listed.
 * ```
 */
export function getETagCacheHandler(
  db: DataStore,
  etagType: ETagType = ETagType.chainTip
): RequestHandler {
  const requestHandler = asyncHandler(async (req, res, next) => {
    const result = await checkETagCacheOK(db, req, etagType);
    if (result === CACHE_OK) {
      // Instruct the client to use the cached response via a `304 Not Modified` response header.
      // This completes the handling for this request, do not call `next()` in order to skip the
      // router handler used for non-cached responses.
      res.set('Cache-Control', CACHE_CONTROL_MUST_REVALIDATE).status(304).send();
    } else {
      // Request does not have a valid cache. Store the etag for later
      // use in setting response cache headers.
      const etag: ETag | undefined = result;
      res.locals[etagType] = etag;
      next();
    }
  });
  return requestHandler;
}
Example #13
Source File: auth.ts    From livepeer-com with MIT License 6 votes vote down vote up
function cors(params: CorsParams): RequestHandler {
  const { baseOpts, anyOriginPathPrefixes, jwtOrigin } = params;
  const anyOriginOpts = { ...baseOpts, origin: true };
  const jwtOpts = { ...baseOpts, origin: jwtOrigin };
  const getCorsOpts = (req: Request) => {
    const { method, path, token } = req;
    const allowAny =
      anyOriginPathPrefixes.some((p) => path.startsWith(p)) ||
      (!token && method === "OPTIONS");
    if (allowAny) {
      return anyOriginOpts;
    } else if (!token) {
      return jwtOpts;
    }
    const allowedOrigins = token.access?.cors?.allowedOrigins ?? [];
    return allowedOrigins.includes("*")
      ? anyOriginOpts
      : {
          ...baseOpts,
          origin: allowedOrigins,
        };
  };

  return corsLib((req, callback) => callback(null, getCorsOpts(req)));
}
Example #14
Source File: api-utils.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
function validateRequest(validationSchema: ValidationSchema): RequestHandler {
  /**
   * In dev environments, as an alternative to token authentication,
   * you can pass the authentication middleware by having a user id in the body.
   * Inject the user id into the schema so that validation will not fail.
   */
  if (process.env.MODE === "dev") {
    validationSchema.body = {
      uid: joi.any(),
      ...(validationSchema.body ?? {}),
    };
  }

  const { validationErrorMessage } = validationSchema;
  const normalizedValidationSchema: ValidationSchema = _.omit(
    validationSchema,
    "validationErrorMessage"
  );

  return (req: MonkeyTypes.Request, _res: Response, next: NextFunction) => {
    _.each(
      normalizedValidationSchema,
      (schema: object, key: keyof ValidationSchema) => {
        const joiSchema = joi.object().keys(schema);

        const { error } = joiSchema.validate(req[key] ?? {});
        if (error) {
          const errorMessage = error.details[0].message;
          throw new MonkeyError(
            422,
            validationErrorMessage ??
              `${errorMessage} (${error.details[0]?.context?.value})`
          );
        }
      }
    );

    next();
  };
}
Example #15
Source File: multer.ts    From advanced-node with GNU General Public License v3.0 6 votes vote down vote up
adaptMulter: RequestHandler = (req, res, next) => {
  const upload = multer().single('picture')
  upload(req, res, error => {
    if (error !== undefined) {
      return res.status(500).json({ error: new ServerError(error).message })
    }
    if (req.file !== undefined) {
      req.locals = { ...req.locals, file: { buffer: req.file.buffer, mimeType: req.file.mimetype } }
    }
    next()
  })
}
Example #16
Source File: wrapExpressHandler.ts    From octane with Apache License 2.0 6 votes vote down vote up
wrapExpressHandler = function (handler: RequestHandler): VercelApiHandler {
    return function (request: VercelRequest, response: VercelResponse): Promise<void> {
        return new Promise<void>(function (resolve, reject) {
            handler(request as any, response as any, function (error?: any) {
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    };
}
Example #17
Source File: wrapExpressHandler.ts    From solana-pay with Apache License 2.0 6 votes vote down vote up
wrapExpressHandler = function (handler: RequestHandler): NextApiHandler {
    return function (request: NextApiRequest, response: NextApiResponse): Promise<void> {
        return new Promise<void>(function (resolve, reject) {
            handler(request as any, response as any, function (error?: any) {
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    };
}
Example #18
Source File: socketMiddleware.ts    From sync-party with GNU General Public License v3.0 6 votes vote down vote up
authenticateSocketRequest = (
    io: Server,
    sessionMiddleware: RequestHandler,
    passport: PassportStatic
) => {
    const socketIoWrap = (middleware: any) => {
        return (
            socket: Socket,
            next: (err?: ExtendedError | undefined) => void
        ) => {
            return middleware(socket.request, {}, next);
        };
    };

    io.use(socketIoWrap(sessionMiddleware));
    io.use(socketIoWrap(passport.initialize()));
    io.use(socketIoWrap(passport.session()));

    io.use((socket, next) => {
        // @ts-ignore
        if (socket.request.user) {
            next();
        } else {
            next(new Error('unauthorized'));
        }
    });
}
Example #19
Source File: middleware.ts    From vircadia-metaverse with Apache License 2.0 6 votes vote down vote up
setupMetaverseAPI: RequestHandler = async (req: Request, resp: Response, next: NextFunction) => {
  req.vRestResp = new RESTResponse(req, resp);
  if (req.socket) {
    req.vSenderKey = `${req.socket.remoteAddress}:${req.socket.remotePort}`;

    req.vSession = Sessions.getSessionWithSenderKey(req.vSenderKey);
    if (req.vSession) {
      Sessions.touchSession(req.vSession);
    }
    else {
      // No existing session for this request
      req.vSession = Sessions.createSession(req.vSenderKey);
      Sessions.addSession(req.vSession);
      Logger.debug('setupMetaverseAPI: created new session for ' + req.vSenderKey);
    };

    let authToken = req.vRestResp.getAuthToken();
    // If an authToken is not supplied in the header, it can be supplied in the query
    if (IsNullOrEmpty(authToken)) {
      if (req.query && req.query.access_token && typeof(req.query.access_token) === 'string') {
        authToken = (req.query.access_token as string);
      };
    };
    if (IsNotNullOrEmpty(authToken)) {
      try {
        req.vAuthToken = await Tokens.getTokenWithToken(authToken);
      }
      catch (err) {
        Logger.error(`setupMetaverseAPI: exception in token lookup: ${err}`);
      };
    };
  };
  next();
}
Example #20
Source File: middlewares.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
launchEditorMiddleware: RequestHandler = (req, res, next) => {
  if (req.url.startsWith(launchEditorEndpoint)) {
    /**
     * retain origin endpoint for backward compatibility <= v1.2.0
     */
    if (
      // relative route used in `Inspector.tsx` `gotoEditor()`
      req.url.startsWith(`${launchEditorEndpoint}/relative`)
      && typeof req.query.fileName === 'string'
    ) {
      req.query.fileName = path.join(process.cwd(), req.query.fileName)
    }

    reactLaunchEditorMiddleware(req, res, next)
  } else {
    next()
  }
}
Example #21
Source File: setup.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Serves the Purpose
   *
   * @returns {IRouter} - Router
   */
  serve(): IRouter {
    this.router.post('/get', (async (req, res) => {
      try {
        const leanHeader = req.headers['x-lean-doc-request'];
        const leanRequest = leanHeader ? true : false;
        const frontendDocs = await this.model.find({}).lean(leanRequest).exec();
        okResponse(res, frontendDocs);
      } catch (e) {
        errorResponseHandler(res, e);
      }
    }) as RequestHandler);

    this.router.delete('/reset', (async (req, res) => {
      try {
        const result = await this.model.clearAll();
        okResponse(res, result);
      } catch (e) {
        errorResponseHandler(res, e);
      }
    }) as RequestHandler);

    return this.router;
  }