express#Response TypeScript 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: ensureAuthenticated.ts    From gobarber-api with MIT License 8 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 #2
Source File: resolver.ts    From one-platform with MIT License 7 votes vote down vote up
function resolver(req: Request, res: Response, next: NextFunction): void {
  const proxy = createProxyMiddleware({
    target: SPASHIP_ROUTER_HOST,
    secure: useSecureSSL,
    changeOrigin: true,
    toProxy: true,
    ignorePath: false,
    headers: {
      'X-OP-Authenticated': req.oidc.isAuthenticated() ? 'true' : 'false',
      ...(req.oidc.isAuthenticated() && {
        'X-OP-Auth-Token': req.oidc.accessToken?.access_token,
      }),
    },
    logProvider: logger.info,
  });

  proxy(req, res, next);
}
Example #3
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 #4
Source File: util.ts    From openapi-cop with MIT License 7 votes vote down vote up
/**
 * Sets a custom openapi-cop validation header ('openapi-cop-validation-result')
 * to the validation results as JSON.
 */
export function setSourceRequestHeader(
  res: Response,
  oasRequest: OasRequest,
): void {
  res.setHeader('openapi-cop-source-request', JSON.stringify(oasRequest));
}
Example #5
Source File: orders.controller.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@httpGet('/:orderId', TYPES.FetchOrderMiddleware)
  public async show(
    {order, user}: Request & {order: Order; user: User},
    re: Response,
  ) {
    if (order.user.id !== user.id) {
      return response.sendStatus(403);
    }
    return ordersSerializer.serialize(order);
  }
Example #6
Source File: DoRequest.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
Perform = async (): Promise<DoRequestResult> => {
        logger.debug("DoRequest with request options:");
        logger.debug(this.parameters.requestOptions)
        const p = new Promise<DoRequestResult>(async (resolve,reject) => {
            try {
                let requestOptions = TransformMtlsOptions(this.parameters.requestOptions)
                let response = await axios.request(requestOptions);
                resolve({error:undefined, response: response,body:response.data})
            } catch (e) {
                resolve({error:e, response: e?.response,body:e?.response?.data})
            }
        });

        return await p;

    }
Example #7
Source File: PostCommentController.ts    From jaebook-server with MIT License 6 votes vote down vote up
@HttpCode(200)
  @Get("/:postId/comments/:id/replies")
  @OpenAPI({
    summary: "Post 댓글 답글 조회",
    responses: {
      "400": {
        description: "Bad request",
      },
    },
    statusCode: "200",
  })
  public async getReply(
    @Param("postId") postId: string,
    @Param("id") commentId: string,
    @Res() res: Response,
  ) {
    const comments = await this.postCommentService.getCommentReplies(
      postId,
      commentId,
    );

    if (comments) {
      return comments;
    } else {
      return res.status(400).send({ message: "잘못된 요청입니다." });
    }
  }
Example #8
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 #9
Source File: index.ts    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
server.on('upgrade', (req: Request, socket: Socket, head: Buffer) => {
  sessionParser(req, {} as Response, () => {
    const parsedURL = parseURL(req.url);
    const path = parsedURL.path;
    const reqOrigin = req.headers['origin'];

    if (reqOrigin !== origin) {
      abortHandshake(socket, 403);
      return;
    }

    if (path === '/admin/ws') {
      adminUpgrade(req, socket, head);
      return;
    }
    if (path === '/ws') {
      userUpgrade(req, socket, head);
      return;
    }
    if (path === '/big-screen/ws') {
      bigScreenUpgrade(req, socket, head);
      return;
    }

    abortHandshake(socket, 404);
  });
});
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: tutorial.router.ts    From frontend.ro with MIT License 6 votes vote down vote up
tutorialRouter.post('/:tutorialId/start', [
  PrivateMiddleware,
  async function startTutorial(req: Request, res: Response) {
    const { tutorialId } = req.params;
    const { user } = req.body;

    if (user.tutorials.includes(tutorialId)) {
      new ServerError(422, `Ai început deja tutorialul cu ID=${tutorialId}`).send(res);
      return;
    }

    try {
      const tutorial = await Tutorial.findOne({ tutorialId });
      if (tutorial === null) {
        new ServerError(404, `Nu există nici un tutorial cu ID=${tutorialId}`).send(res);
        return;
      }

      await UserModel.update(user._id, { tutorials: [...user.tutorials, tutorialId] });
    } catch (err) {
      new ServerError(
        err.code || 500,
        err.message || `Error tying to start tutorial with ID=${tutorialId}`,
      ).send(res);
    }

    res.status(200).send();
  }
])
Example #12
Source File: metrics.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
//

  public static endpoint() {
    return async function (_req: Request, res: Response) {
      res
        .status(200)
        .header({ 'Content-Type': 'text/plain' })
        .send(await Metrics.register.metrics())
    }
  }
Example #13
Source File: index.ts    From context-mod with MIT License 6 votes vote down vote up
cancelDelayed = async (req: Request, res: Response) => {

    const {id} = req.query as any;
    const {name: userName} = req.user as Express.User;

    if(req.manager?.resources === undefined) {
        req.manager?.logger.error('Subreddit does not have delayed items!', {user: userName});
        return res.status(400).send();
    }

    const delayedItem = req.manager.resources.delayedItems.find(x => x.id === id);
    if(delayedItem === undefined) {
        req.manager?.logger.error(`No delayed items exists with the id ${id}`, {user: userName});
        return res.status(400).send();
    }

    req.manager.resources.delayedItems = req.manager.resources.delayedItems.filter(x => x.id !== id);
    req.manager?.logger.info(`Remove Delayed Item '${delayedItem.id}'`, {user: userName});
    return res.send('OK');
}
Example #14
Source File: app.ts    From FlareSolverr with MIT License 6 votes vote down vote up
// Errors
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
    if (err) {
        let msg = 'Invalid request: ' + err;
        msg = msg.replace("\n", "").replace("\r", "")
        log.error(msg)
        res.send({"error": msg})
    } else {
        next()
    }
})
Example #15
Source File: http-responses.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/**
 * Returns an internal server error response with 500 status code.
 * @param response The http-response to be modified.
 * @param error The error or error-message to be sent within the response' body.
 */
export function InternalServerError(response: Response, error: string | Error): Response {
  const body: AppHttpResponse = {
    errors: [
      {
        code: AppErrorCode.InternalServerError,
        title: 'Internal server error',
        detail: typeof error === 'string' ? error : error.message
      }
    ]
  };
  return response.status(500).send(body);
}
Example #16
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.log(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});
Example #17
Source File: server.ts    From gobarber-api with MIT License 6 votes vote down vote up
app.use((err: Error, req: Request, res: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  // eslint-disable-next-line
  console.error(err);

  return res.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});
Example #18
Source File: test-target-servers.ts    From openapi-cop with MIT License 6 votes vote down vote up
STRICTLY_NON_COMPLIANT_SERVERS: {
  [dir: string]: NonCompliantServerConfigMap;
} = {
  v3: {
    '2-path.yaml': [
      {
        request: {
          method: 'POST',
          url: '/echo',
          data: JSON.stringify({ input: 'ECHO!' }),
        },
        runServer: responderTo(
          'post',
          '/echo',
          (_req: Request, res: Response) => {
            res
              .status(200)
              .json({ output: 'The cake is a lie', forrest: 'Gump' });
          },
        ),
        expectedError: { keyword: 'additionalProperties' },
      },
    ],
  },
}
Example #19
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 #20
Source File: util.d.ts    From openapi-cop with MIT License 6 votes vote down vote up
/**
 * Sets a custom openapi-cop validation header ('openapi-cop-validation-result')
 * to the validation results as JSON.
 */
export declare function setValidationHeader(res: Response, validationResults: ValidationResults): void;
Example #21
Source File: UserHandler.ts    From node-experience with MIT License 6 votes vote down vote up
@httpPut('/change-user-password/:id', AuthorizeMiddleware(Permissions.USERS_CHANGE_USER_PASSWORD))
    public async changeUserPassword(@request() req: Request, @response() res: Response): Promise<void>
    {
        const _request = new ChangeUserPasswordRequest(req.body, req.params.id);

        const user: IUserDomain = await this.controller.changeUserPassword(_request);

        void await this.responder.send(user, req, res, StatusCode.HTTP_CREATED, new DefaultMessageTransformer(ResponseMessageEnum.UPDATED));
    }
Example #22
Source File: ItemsController.ts    From NLW-1.0 with MIT License 6 votes vote down vote up
async index(request: Request, response: Response) {
    const items = await knex('items').select('*');

    const serializedItems = items.map(item => {
      return {
        id: item.id,
        title: item.title,
        image_url: `http://192.168.0.156:3333/uploads/${item.image}`,
      };
    });

    return response.json(serializedItems);
  }
Example #23
Source File: restHandler.ts    From AIPerf with MIT License 6 votes vote down vote up
private getLatestMetricData(router: Router): void {
        router.get('/metric-data-latest/', async (req: Request, res: Response) => {
            this.nniManager.getLatestMetricData().then((metricsData: MetricDataRecord[]) => {
                res.send(metricsData);
            }).catch((err: Error) => {
                this.handleError(err, res);
            });
        });
    }
Example #24
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 #25
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 #26
Source File: Responder.ts    From node-experience with MIT License 6 votes vote down vote up
public render(data: any, view: any, response: Response, resolve: any, reject: any)
    {
        response.render('log', { data }, (err: any, compiled: any) =>
        {
            if (err)
            {
                // eslint-disable-next-line @typescript-eslint/no-unsafe-call
                reject('500 when rendering the template');
            }
            // eslint-disable-next-line @typescript-eslint/no-unsafe-call
            resolve(compiled);
        });
    }