express#NextFunction TypeScript Examples

The following examples show how to use express#NextFunction. 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: server-utils.ts    From anthem with Apache License 2.0 7 votes vote down vote up
requestLogger = (
  req: Request,
  _: Response,
  next: NextFunction,
) => {
  if (ENV.ENABLE_LOGGING) {
    const { body } = req;
    const { operationName, variables } = body;

    // Don't log introspection query (clutter):
    if (Boolean(operationName) && operationName !== "IntrospectionQuery") {
      console.log(chalk.blue("Request Received:"));
      console.log(
        `- Query: ${operationName}\n- Variables: ${JSON.stringify(
          variables,
        )}\n`,
      );
    }
  }

  return next();
}
Example #2
Source File: resolver.ts    From one-platform with MIT License 6 votes vote down vote up
export default function resolver(
  req: Request,
  res: Response,
  next: NextFunction
): void {
  const { uid, role, rhatUUID } = res.locals.user;

  /* Adding additional roles */
  role.push('user:' + uid, 'user:' + rhatUUID, 'op-users');

  const token = createHmac('sha1', COUCHDB_SECRET as string)
    .update(uid) // lgtm[js/weak-cryptographic-algorithm]
    .digest('hex');

  const proxy = createProxyMiddleware({
    target: COUCHDB_HOST,
    secure: useSecureSSL,
    changeOrigin: true,
    headers: {
      'X-Auth-CouchDB-UserName': uid,
      'X-Auth-CouchDB-Roles': role.join(','),
      'X-Auth-CouchDB-Token': token,
    },
    pathRewrite: {
      ['^/api/couchdb']: '',
    },
  });
  proxy(req, res, next);
}
Example #3
Source File: askExpressMiddleware.ts    From askql with MIT License 6 votes vote down vote up
export function askExpressMiddleware(
  environment: AskEnvironment,
  config: AskExpressMiddlewareConfig = {
    callNext: true,
    passError: false,
  }
) {
  return async function (
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    try {
      const parsedCode = getParsedCode(request.body);
      const queryResponse = await runUntyped(environment, parsedCode);
      response.json(queryResponse);

      if (config.callNext) {
        return next();
      }
    } catch (err) {
      config.passError && next(err);
      return;
    }
    return;
  };
}
Example #4
Source File: httpErrorHandler.middleware.ts    From Graphql-api with ISC License 6 votes vote down vote up
function errorMiddleware(
  error: HttpException,
  request: Request,
  response: Response,
  next: NextFunction
): void {
  const status: number = error.status || 500;
  const message: string = error.message || 'Something went wrong';
  response.status(status).send({
    status,
    message
  });
  next({ err: message });
}
Example #5
Source File: LogHandler.ts    From node-experience with MIT License 6 votes vote down vote up
@httpGet('/')
    public async log(@request() req: Request, @response() res: Response, @next() nex: NextFunction)
    {
        return new Promise<string>((resolve, reject) =>
        {
            const use_case = new GetLogViewUseCase();
            const data = use_case.handle();

            this.responder.render(data, 'log', res, resolve, reject);
        });
    }
Example #6
Source File: ensureAuthenticated.ts    From gobarber-api with MIT License 6 votes vote down vote up
export default function ensureAuthenticated(
  req: Request,
  res: Response,
  next: NextFunction,
): void {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    throw new AppError('JWT token is missing', 401);
  }

  const [, token] = authHeader.split(' ');

  try {
    const decoded = verify(token, authConfig.jwt.secret);

    const { sub } = decoded as ITokenPayload;

    req.user = {
      id: sub,
    };

    return next();
  } catch {
    throw new AppError('Invalid JWT token', 401);
  }
}
Example #7
Source File: app.ts    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return response.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  console.error(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});
Example #8
Source File: categories.routes.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/* Create new category route. */
categoriesRouter.post('', createCategoryValidator, async (req: Request, res: Response, next: NextFunction) => {
  try {
    /** The validation errors that may result from validating request [body', 'cookies', 'headers', 'params' or 'query' ] */
    const validationErrors = validationResult(req)
      .formatWith(validationErrorFormatter)
      .array({ onlyFirstError: true });

    if (validationErrors.length) {
      return BadRequest(res, { errors: validationErrors });
    }

    const data: CreateCategoryInput = req.body;
    const result = await CategoriesDataAccess.create(data);

    if (result.error) {
      next(result.error);
    } else if (result.validationErrors && result.validationErrors.length) {
      BadRequest(res, { errors: result.validationErrors });
    } else if (result.data) {
      Ok(res, { data: result.data });
    }
  } catch (error) {
    next(error);
  }
});
Example #9
Source File: app.ts    From FlareSolverr with MIT License 6 votes vote down vote up
// Access log
app.use(function(req: Request, res: Response, next: NextFunction) {
    if (req.url != '/health') {
        // count the request for the log prefix
        log.incRequests()
        // build access message
        let body = "";
        if (req.method == 'POST' && req.body) {
            body += " body: "
            try {
                body += JSON.stringify(req.body)
            } catch(e) {
                body += req.body
            }
        }
        log.info(`Incoming request => ${req.method} ${req.url}${body}`);
    }
    next();
});
Example #10
Source File: server.ts    From GiveNGo with MIT License 6 votes vote down vote up
// Global Error handler
app.use(
  (
    err: ErrorRequestHandler,
    req: Request,
    res: Response,
    next: NextFunction
  ) => {
    // Set up default error
    const defaultError = {
      log: 'Error caught in global error handler',
      status: 500,
      msg: {
        err: err,
      },
    };

    // Update default error message with provided error if there is one
    const output = Object.assign(defaultError, err);
    res.send(output);
  }
);
Example #11
Source File: createRouter.ts    From davinci with MIT License 6 votes vote down vote up
wrapMiddleware = middlewareFn => {
	// it's an error middleware
	if (middlewareFn.length === 4) {
		return (err: Error, req: DaVinciRequest, res: Response, next: NextFunction) => {
			if (req.requestHandled) return next();

			return middlewareFn(err, req, res, next);
		};
	}
	return (req: DaVinciRequest, res: Response, next: NextFunction) => {
		if (req.requestHandled) return next();

		return middlewareFn(req, res, next);
	};
}
Example #12
Source File: AuthMiddleware.ts    From jaebook-server with MIT License 6 votes vote down vote up
checkAccessToken = (
  req: Request,
  res: Response,
  next: NextFunction,
) => {
  const token = extractAccessToken(req);
  let jwtPayload;

  try {
    jwtPayload = jwt.verify(token, env.app.jwtAccessSecret);
    res.locals.jwtPayload = jwtPayload;
  } catch (error) {
    return res.status(401).send({ message: "Invalid or Missing JWT token" });
  }

  next();
}
Example #13
Source File: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 6 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 #14
Source File: errors.ts    From hotseat-api with MIT License 6 votes vote down vote up
errorHandler = (
  error: Error,
  request: Request,
  response: Response,
  _: NextFunction,
): Response => {
  if (process.env.NODE_ENV === 'development') {
    // eslint-disable-next-line no-console
    console.error(error);
  }

  if (error instanceof AppError) {
    return response.status(error.statusCode).json({
      status: 'error',
      message: error.message,
    });
  }

  return response.status(500).json({
    status: 'error',
    message: 'Internal Server Error',
  });
}
Example #15
Source File: index.ts    From webhook-proxy with MIT License 6 votes vote down vote up
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
    if (err instanceof SyntaxError && 'body' in err) {
        return res.status(400).json({
            proxy: true,
            error: 'Malformed request. The proxy only accepts valid JSON bodies.'
        });
    }

    error('error encountered:', err, 'by', req.params.id ?? req.ip);

    return res.status(500).json({
        proxy: true,
        error: 'An error occurred while processing your request.'
    });
});
Example #16
Source File: user.ts    From dropify with MIT License 6 votes vote down vote up
signInUser = asyncMiddleware(
  async (req: Request, res: Response, next: NextFunction) => {
    const { email, password, userName } = req.body;
    if (!(email || userName) || !password) {
      return next(new ErrorResponse(`enter email/userName and password`, 400));
    }

    const user = await User.findOne({
      $or: [{ email }, { userName }],
    })
      .select("+password")
      .exec();

    if (!user || !(await user.correctPassword(user.password, password))) {
      return next(new ErrorResponse(`Invalid email or password`, 401));
    }

    const token = await generateUserToken(user._id);

    res.status(200).send({
      status: "success",
      token,
    });
  }
)
Example #17
Source File: helpers.ts    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
ensureAuthenticated = (req: Request, res: Response, next: NextFunction) => {
  if (req.isAuthenticated()) {
    return next();
  }
  /* istanbul ignore next */
  res.status(401).send({
    error: "Unauthorized",
  });
}
Example #18
Source File: adminApiHeaders.ts    From paystring with Apache License 2.0 6 votes vote down vote up
/**
 * A middleware asserting that Admin requests have an appropriate Content-Type header.
 *
 * @param req - An Express Request object.
 * @param _res - An Express Response object.
 * @param next - An Express next() function.
 * @throws A ParseError if the Content-Type header is missing, malformed, or unsupported.
 */
export function checkRequestContentType(
  req: Request,
  _res: Response,
  next: NextFunction,
): void {
  type MimeType = 'application/json' | 'application/merge-patch+json'
  // The default media type required is 'application/json' for POST and PUT requests
  let mediaType: MimeType = 'application/json'

  if (req.method === 'PATCH') {
    /**
     * The required Content-Type header for the PATCH endpoints is 'application/merge-patch+json'.
     *
     * The merge patch format is primarily intended for use with the HTTP PATCH method
     * as a means of describing a set of modifications to a target resource’s content.
     * Application/merge-patch+json is a Type Specific Variation of the "application/merge-patch" Media Type that uses a
     * JSON data structure to describe the changes to be made to a target resource.
     */
    mediaType = 'application/merge-patch+json'
  }

  // POST, PUT and PATCH requests need a valid Content-Type header
  if (
    req.header('Content-Type') !== mediaType &&
    ['POST', 'PUT', 'PATCH'].includes(req.method)
  ) {
    throw new ContentTypeError(mediaType)
  }

  next()
}
Example #19
Source File: logger.middleware.spec.ts    From whispr with MIT License 6 votes vote down vote up
describe('Logger Middleware', () => {
  it('log should hide token', () => {
    expect(headersToString({ atest: 'aValue', authorization: 'Bearer thatShouldBeHidden' })).toBe(
      '{"atest":"aValue","authorization":"[HIDDEN size=25]"}',
    );
  });
  it('middleware should let go through', () => {
    const next = jest.fn() as unknown as NextFunction;
    const res = jest.fn() as unknown as Response;

    const req = { headers: { atest: 'aValue', authorization: 'Bearer thatShouldBeHidden' } } as unknown as Request;
    logger(req, res, next);
    expect(next).toHaveBeenCalled();
  });
});
Example #20
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 #21
Source File: app.ts    From ecoleta with MIT License 6 votes vote down vote up
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return response.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  console.log(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});
Example #22
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
errorHandler = (log: Logger) => (
  err: HttpError,
  req: Request,
  res: Response,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  next: NextFunction
): void => {
  if (!err)
    err = new InternalServerError(
      'An unknown error occurred in the errorHandler'
    );
  if (!err.status) err = new InternalServerError(err.message);

  if (err.status >= 500) {
    log.error(`${err.status}`, err);
  } else {
    // otherwise just log the error message at the warning level
    log.warn(`${err.status}: ${err.message}`);
  }
  res.status(err.status).json({
    error: {
      status: err.status,
      message: `${err.message}`,
    },
  });
}