fastify#FastifyRequest TypeScript Examples

The following examples show how to use fastify#FastifyRequest. 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: utils.ts    From postgres-meta with Apache License 2.0 7 votes vote down vote up
extractRequestForLogging = (request: FastifyRequest) => {
  let pg: string = 'unknown'
  try {
    if (request.headers.pg) {
      pg = parse(request.headers.pg as string).host || pg
    }
  } catch (e: any) {
    console.warn('failed to parse PG connstring for ' + request.url)
  }

  const additional = request.headers['x-supabase-info']?.toString() || ''

  return {
    method: request.method,
    url: request.url,
    pg,
    opt: additional,
  }
}
Example #2
Source File: carsController.ts    From node-fastify-mongo-api with MIT License 6 votes vote down vote up
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 #3
Source File: carsController.ts    From node-fastify-mongo-api with MIT License 6 votes vote down vote up
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 #4
Source File: carsController.ts    From node-fastify-mongo-api with MIT License 6 votes vote down vote up
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: decorator.spec.ts    From nestjs-paginate with MIT License 6 votes vote down vote up
function fastifyContextFactory(query: FastifyRequest['query']): Partial<ExecutionContext> {
    const mockContext: Partial<ExecutionContext> = {
        switchToHttp: (): HttpArgumentsHost =>
            Object({
                getRequest: (): Partial<FastifyRequest> =>
                    Object({
                        protocol: 'http',
                        hostname: 'localhost',
                        url: '/items?search=2423',
                        query: query,
                    }),
            }),
    }
    return mockContext
}
Example #6
Source File: postgrest.ts    From storage-api with Apache License 2.0 6 votes vote down vote up
async function getPostgrestClient(request: FastifyRequest, jwt: string): Promise<PostgrestClient> {
  const { anonKey, isMultitenant, postgrestURL, postgrestURLSuffix, xForwardedHostRegExp } =
    getConfig()
  let url = postgrestURL
  let apiKey = anonKey
  if (isMultitenant && xForwardedHostRegExp) {
    const xForwardedHost = request.headers['x-forwarded-host']
    if (typeof xForwardedHost !== 'string') {
      throw new Error('X-Forwarded-Host header is not a string')
    }
    if (!new RegExp(xForwardedHostRegExp).test(xForwardedHost)) {
      throw new Error('X-Forwarded-Host header does not match regular expression')
    }
    url = `http://${xForwardedHost}${postgrestURLSuffix}`
    apiKey = await getAnonKey(request.tenantId)
  }
  const postgrest = new PostgrestClient(url, {
    headers: {
      apiKey,
      Authorization: `Bearer ${jwt}`,
    },
    schema: 'storage',
  })
  return postgrest
}
Example #7
Source File: carsController.ts    From node-fastify-mongo-api with MIT License 5 votes vote down vote up
getCars = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>): Promise<Document[]> => {
	try {
		const cars = await Car.find();
		return cars;
	} catch (err) {
		throw boom.boomify(err);
	}
}
Example #8
Source File: carsController.ts    From node-fastify-mongo-api with MIT License 5 votes vote down vote up
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 #9
Source File: main.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
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 #10
Source File: fastify.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
export function requestFromFastify(req: FastifyRequest) {
  return new OAuthRequest({
    query: <Record<string, unknown>>req.query ?? {},
    body: <Record<string, unknown>>req.body ?? {},
    headers: <Record<string, unknown>>req.headers ?? {},
  });
}
Example #11
Source File: index.ts    From mercurius-typescript with MIT License 5 votes vote down vote up
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
  return {
    authorization: req.headers.authorization,
  }
}
Example #12
Source File: index.ts    From mercurius-typescript with MIT License 5 votes vote down vote up
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
  return {
    authorization: req.headers.authorization,
  }
}
Example #13
Source File: index.ts    From mercurius-typescript with MIT License 5 votes vote down vote up
buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
  return {
    authorization: req.headers.authorization,
  }
}
Example #14
Source File: query.ts    From postgres-meta with Apache License 2.0 5 votes vote down vote up
errorOnEmptyQuery = (request: FastifyRequest) => {
  if (!(request.body as any).query) {
    throw new Error('query not found')
  }
}
Example #15
Source File: getObject.ts    From storage-api with Apache License 2.0 5 votes vote down vote up
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))
  }
}