fastify#FastifyReply TypeScript Examples
The following examples show how to use
fastify#FastifyReply.
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: file.controller.ts From whispr with MIT License | 6 votes |
@Get('*')
async getFile(@Param('*') key: string, @Res() response: FastifyReply): Promise<void> {
try {
const file = await this.fileService.getFile(key);
response.type(file.ContentType);
response.send(file.Body);
} catch (error) {
Logger.error(error);
response.status(404);
response.send();
}
}
Example #2
Source File: fastify.ts From ts-oauth2-server with MIT License | 6 votes |
export function handleFastifyError(e: unknown | OAuthException, res: FastifyReply) {
if (e instanceof OAuthException) {
res.status(e.status).send({
status: e.status,
message: e.message,
});
return;
}
throw e;
}
Example #3
Source File: fastify.ts From ts-oauth2-server with MIT License | 6 votes |
export function handleFastifyReply(res: FastifyReply, response: OAuthResponse) {
if (response.status === 302) {
if (!response.headers.location) throw new Error("missing redirect location");
res.headers(response.headers);
res.redirect(response.headers.location);
} else {
res.headers(response.headers);
res.status(response.status).send(response.body);
}
}
Example #4
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 6 votes |
deleteCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const id = req.params.id;
const car = await Car.findByIdAndRemove(id);
return car;
} catch (err) {
throw boom.boomify(err);
}
}
Example #5
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 6 votes |
updateCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const id = req.params.id;
const car = req.body;
const { ...updateData } = car;
const update = await Car.findByIdAndUpdate(id, updateData, { new: true });
return update;
} catch (err) {
throw boom.boomify(err);
}
}
Example #6
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 6 votes |
getSingleCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const id = req.params.id;
const car = await Car.findById(id);
return car;
} catch (err) {
throw boom.boomify(err);
}
}
Example #7
Source File: plugin.ts From fastify-sse-v2 with MIT License | 6 votes |
plugin: FastifyPluginAsync<SsePluginOptions> =
async function (instance, options): Promise<void> {
instance.decorateReply(
"sse",
function (this: FastifyReply, source: AsyncIterable<EventMessage>): void {
Object.entries(this.getHeaders()).forEach(([key, value]) => {
this.raw.setHeader(key, value);
});
this.raw.setHeader("Content-Type","text/event-stream");
this.raw.setHeader("Connection", "keep-alive");
this.raw.setHeader("Cache-Control", "no-cache,no-transform");
this.raw.setHeader("x-no-compression", 1);
this.raw.write(serializeSSEEvent({retry: options.retryDelay || 3000}));
toStream(transformAsyncIterable(source)).pipe(this.raw);
});
}
Example #8
Source File: cms.service.ts From Cromwell with MIT License | 6 votes |
async downloadFile(response: FastifyReply, inPath: string, fileName: string) {
const fullPath = join(getPublicDir(), inPath ?? '', fileName);
if (! await fs.pathExists(fullPath)) {
response.code(404).send({ message: 'File not found' });
return;
}
if ((await fs.lstat(fullPath)).isFile()) {
response.header('Content-Disposition', `attachment; filename=${fileName}`);
try {
const readStream = fs.createReadStream(fullPath);
response.type('text/html').send(readStream);
} catch (error) {
logger.error(error);
response.code(500).send({ message: error + '' });
}
} else {
response.header('Content-Disposition', `attachment; filename=${fileName}.zip`);
// zip the directory
const archive = archiver('zip', {
zlib: { level: 9 }
});
archive.directory(fullPath, '/' + fileName);
response.type('text/html').send(archive);
await archive.finalize();
}
}
Example #9
Source File: auth.controller.ts From Cromwell with MIT License | 6 votes |
@Post('login')
@UseGuards(ThrottlerGuard)
@Throttle(10, 30)
@ApiOperation({
description: 'Authenticates a human user via cookies.',
})
@ApiBody({ type: LoginDto })
@ApiResponse({
status: 200,
type: UserDto
})
async login(@Request() req: TRequestWithUser, @Response() response: FastifyReply, @Body() input: LoginDto) {
let authInfo: TLoginInfo = null;
try {
authInfo = await this.authService.logIn(input);
} catch (error) {
logger.error(error);
}
if (!authInfo) {
response.status(403);
response.send({ message: 'Login failed', statusCode: 403 });
return;
}
req.user = authInfo.userInfo;
if (authInfo.refreshToken && authInfo.accessToken) {
this.authService.setAccessTokenCookie(response, req,
this.authService.getAccessTokenInfo(authInfo.accessToken));
this.authService.setRefreshTokenCookie(response, req,
this.authService.getRefreshTokenInfo(authInfo.refreshToken));
}
response.code(200).send(authInfo.userDto);
}
Example #10
Source File: rest-exception.filter.ts From Cromwell with MIT License | 6 votes |
public async catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<FastifyReply>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
const message = exception.message || "Internal error";
response
.status(status)
.send({
message,
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
Example #11
Source File: cms.controller.ts From Cromwell with MIT License | 6 votes |
@Post('export-db')
@UseGuards(JwtAuthGuard)
@Roles('administrator', 'guest')
@ApiOperation({
description: `Exports DB into Excel file`,
})
@ApiBody({ type: ExportOptionsDto })
@ApiResponse({
status: 200,
})
async exportDB(@Body() input: ExportOptionsDto, @Response() response: FastifyReply) {
if (!Array.isArray(input.tables)) input.tables = [];
try {
const file = await this.migrationService.exportDB(input.tables as any);
response.type('text/html').send(file);
} catch (error) {
logger.error(error);
response.code(500).send({ message: error + '' });
}
}
Example #12
Source File: cms.controller.ts From Cromwell with MIT License | 6 votes |
@Get('download-public-file')
@UseGuards(JwtAuthGuard)
@Roles('administrator', 'guest', 'author')
@ApiOperation({
description: 'Downloads a file from specified subfolder of "public" files',
parameters: [
{ name: 'inPath', in: 'query' },
{ name: 'fileName', in: 'query' }]
})
@ApiResponse({
status: 200,
})
@ApiForbiddenResponse({ description: 'Forbidden.' })
async downloadFile(@Query('inPath') inPath: string, @Query('fileName') fileName: string,
@Response() response: FastifyReply) {
logger.log('CmsController::downloadFile');
return this.cmsService.downloadFile(response, inPath, fileName);
}
Example #13
Source File: auth.controller.ts From Cromwell with MIT License | 6 votes |
@UseGuards(JwtAuthGuard)
@Post('log-out')
@ApiOperation({
description: 'Logs user out who was logged via cookies',
})
async logOut(@Request() request: TRequestWithUser, @Response() response: FastifyReply) {
if (request.user) {
try {
await this.authService.removeRefreshTokens(request.user);
} catch (error) {
logger.error(error);
}
}
this.authService.clearTokenCookies(response, request);
response.code(200).send(true);
}
Example #14
Source File: getObject.ts From storage-api with Apache License 2.0 | 5 votes |
async function requestHandler(
request: FastifyRequest<getObjectRequestInterface, Server, IncomingMessage>,
response: FastifyReply<
Server,
IncomingMessage,
ServerResponse,
getObjectRequestInterface,
unknown
>
) {
const { bucketName } = request.params
const objectName = request.params['*']
if (!isValidKey(objectName) || !isValidKey(bucketName)) {
return response
.status(400)
.send(createResponse('The key contains invalid characters', '400', 'Invalid key'))
}
const objectResponse = await request.postgrest
.from<Obj>('objects')
.select('id')
.match({
name: objectName,
bucket_id: bucketName,
})
.single()
if (objectResponse.error) {
const { status, error } = objectResponse
request.log.error({ error }, 'error object')
return response.status(400).send(transformPostgrestError(error, status))
}
// send the object from s3
const s3Key = `${request.tenantId}/${bucketName}/${objectName}`
request.log.info(s3Key)
try {
const data = await storageBackend.getObject(globalS3Bucket, s3Key, {
ifModifiedSince: request.headers['if-modified-since'],
ifNoneMatch: request.headers['if-none-match'],
range: request.headers.range,
})
response
.status(data.metadata.httpStatusCode ?? 200)
.header('Accept-Ranges', 'bytes')
.header('Content-Type', normalizeContentType(data.metadata.mimetype))
.header('Cache-Control', data.metadata.cacheControl)
.header('ETag', data.metadata.eTag)
.header('Content-Length', data.metadata.contentLength)
.header('Last-Modified', data.metadata.lastModified)
if (data.metadata.contentRange) {
response.header('Content-Range', data.metadata.contentRange)
}
return response.send(data.body)
} catch (err: any) {
if (err.$metadata?.httpStatusCode === 304) {
return response.status(304).send()
}
request.log.error(err)
return response.status(400).send(createResponse(err.message, '400', err.name))
}
}
Example #15
Source File: index.ts From mercurius-typescript with MIT License | 5 votes |
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
return {
authorization: req.headers.authorization,
}
}
Example #16
Source File: index.ts From mercurius-typescript with MIT License | 5 votes |
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
return {
authorization: req.headers.authorization,
}
}
Example #17
Source File: index.ts From mercurius-typescript with MIT License | 5 votes |
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
return {
authorization: req.headers.authorization,
}
}
Example #18
Source File: fastify.ts From ts-oauth2-server with MIT License | 5 votes |
export function responseFromFastify(res: FastifyReply) {
return new OAuthResponse({
headers: <Record<string, unknown>>(<unknown>res.headers) ?? {},
});
}
Example #19
Source File: main.ts From ts-oauth2-server with MIT License | 5 votes |
async function bootstrap() {
const prisma = new PrismaClient();
const authorizationServer = new AuthorizationServer(
new AuthCodeRepository(prisma.oAuthAuthCode),
new ClientRepository(prisma.oAuthClient),
new TokenRepository(prisma.oAuthToken),
new ScopeRepository(prisma.oAuthScope),
new UserRepository(prisma.user),
new JwtService(process.env.OAUTH_CODES_SECRET!),
);
authorizationServer.enableGrantTypes(
["authorization_code", new DateInterval("15m")],
["client_credentials", new DateInterval("1d")],
"refresh_token",
"password",
"implicit",
);
const fastify = Fastify({ logger: true });
fastify.get("/authorize", async (req: FastifyRequest, res: FastifyReply) => {
try {
// Validate the HTTP request and return an AuthorizationRequest object.
const authRequest = await authorizationServer.validateAuthorizationRequest(requestFromFastify(req));
// The auth request object can be serialized and saved into a user's session.
// You will probably want to redirect the user at this point to a login endpoint.
// Once the user has logged in set the user on the AuthorizationRequest
console.log("Once the user has logged in set the user on the AuthorizationRequest");
authRequest.user = { id: "abc", email: "[email protected]" };
// At this point you should redirect the user to an authorization page.
// This form will ask the user to approve the client and the scopes requested.
// Once the user has approved or denied the client update the status
// (true = approved, false = denied)
authRequest.isAuthorizationApproved = true;
// Return the HTTP redirect response
const oauthResponse = await authorizationServer.completeAuthorizationRequest(authRequest);
return handleFastifyReply(res, oauthResponse);
} catch (e) {
handleFastifyError(e, res);
}
});
fastify.post("/token", async (req: FastifyRequest, res: FastifyReply) => {
const request = requestFromFastify(req);
try {
const oauthResponse = await authorizationServer.respondToAccessTokenRequest(request);
return handleFastifyReply(res, oauthResponse);
} catch (e) {
handleFastifyError(e, res);
return;
}
});
fastify.get("/", (_req: FastifyRequest, res: FastifyReply) => {
res.send({
success: true,
GET: ["/authorize"],
POST: ["/token"],
});
});
await fastify.listen(3000);
console.log("app is listening on localhost:3000");
}
Example #20
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 5 votes |
addCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const car = new Car(req.body);
return await car.save();
} catch (err) {
throw boom.boomify(err);
}
}
Example #21
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 5 votes |
getCars = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>): Promise<Document[]> => {
try {
const cars = await Car.find();
return cars;
} catch (err) {
throw boom.boomify(err);
}
}
Example #22
Source File: auth.service.ts From Cromwell with MIT License | 5 votes |
async processRequest(request: TRequestWithUser, response: FastifyReply): Promise<TAuthUserInfo | null> {
try {
const authHeader = String(request?.headers?.['authorization'] ?? '');
if (authHeader.startsWith('Service ')) {
// Access by secret token from other services such as Renderer
const serviceSecret = authHeader.substring(8, authHeader.length);
if (serviceSecret === this.authSettings.serviceSecret) {
request.user = {
id: 111,
email: 'service',
role: 'administrator',
}
return request.user;
}
}
let accessToken = request?.cookies?.[this.authSettings.accessTokenCookieName];
const refreshToken = request?.cookies?.[this.authSettings.refreshTokenCookieName];
if (!accessToken) {
if (authHeader.startsWith('Bearer ')) {
accessToken = authHeader.substring(7, authHeader.length);
}
}
if (!accessToken && !refreshToken) return null;
// Validate access token
const accessTokenPayload = accessToken ? await this.validateAccessToken(accessToken) : undefined;
if (accessTokenPayload) {
request.user = this.payloadToUserInfo(accessTokenPayload)
return request.user;
}
// If access token is expired, validate refresh token
if (!refreshToken || refreshToken === 'null')
throw new UnauthorizedException('Refresh token is not set');
const refreshTokenPayload = await this.validateRefreshToken(refreshToken);
if (!refreshTokenPayload)
throw new UnauthorizedException('Refresh token is not valid');
const authUserInfo = this.payloadToUserInfo(refreshTokenPayload);
// Check that token is in DB and was not blacklisted
const validUser = await this.dbCheckRefreshToken(refreshToken, authUserInfo);
if (!validUser)
throw new UnauthorizedException('Refresh token is not valid');
request.user = authUserInfo;
// Create new access token
const newAccessToken = await this.generateAccessToken(authUserInfo);
// Update refresh token
const newRefreshToken = await this.updateRefreshToken(authUserInfo, validUser);
if (!newRefreshToken)
throw new UnauthorizedException('Failed to update refresh token');
this.setAccessTokenCookie(response, request, newAccessToken);
this.setRefreshTokenCookie(response, request, newRefreshToken);
return authUserInfo;
} catch (err: any) {
logger.log('processRequest: ', err.message);
this.clearTokenCookies(response, request);
}
return null;
}