Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18,011 changes: 7,113 additions & 10,898 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
"typescript": "^5.0.2"
},
"dependencies": {
"@fastify/cors": "^8.0.0",
"@fastify/swagger": "^8.3.1",
"@fastify/type-provider-typebox": "^3.2.0",
"fastify": "^4.3.0",
"fastify-metrics": "^10.2.0",
"node-pg-migrate": "^6.2.2",
"pino": "^8.11.0",
"postgres": "^3.3.4"
Expand Down
46 changes: 46 additions & 0 deletions src/fastify/fastify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import FastifyCors from '@fastify/cors';
import Fastify, { FastifyInstance } from 'fastify';
import FastifyMetrics, { IFastifyMetrics } from 'fastify-metrics';
import { PINO_LOGGER_CONFIG } from '../logger';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { isProdEnv } from '../helpers';

/**
* Creates a Fastify server that handles Prometheus metrics and CORS headers automatically.
* @returns Fastify instance
*/
export async function buildFastifyApiServer(): Promise<FastifyInstance> {
const fastify = Fastify({
trustProxy: true,
logger: PINO_LOGGER_CONFIG,
}).withTypeProvider<TypeBoxTypeProvider>();
if (isProdEnv) {
await fastify.register(FastifyMetrics, { endpoint: null });
}
await fastify.register(FastifyCors);
return fastify;
}

/**
* Creates a Fastify server that serves a `/metrics` endpoint with metrics taken from
* `FastifyMetrics`.
* @param args - Fastify instance metrics decorator
* @returns Fastify instance
*/
export async function buildPrometheusServer(args: {
metrics: IFastifyMetrics;
}): Promise<FastifyInstance> {
const promServer = Fastify({
trustProxy: true,
logger: PINO_LOGGER_CONFIG,
});
promServer.route({
url: '/metrics',
method: 'GET',
logLevel: 'info',
handler: async (_, reply) => {
await reply.type('text/plain').send(await args.metrics.client.register.metrics());
},
});
return promServer;
}
2 changes: 2 additions & 0 deletions src/fastify/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './fastify';
export * from './openapi';
30 changes: 30 additions & 0 deletions src/fastify/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import Fastify, { FastifyPluginAsync, FastifyPluginCallback } from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { SwaggerOptions } from '@fastify/swagger';
import FastifySwagger from '@fastify/swagger';
import { existsSync, mkdirSync, writeFileSync } from 'fs';

export interface OpenApiGeneratorOptions {
apiDefinition: FastifyPluginAsync | FastifyPluginCallback;
swaggerOptions?: SwaggerOptions;
prefix?: string;
outputDirectory?: string;
}

/**
* Generates OpenAPI JSON and YAML spec documents based on a given Fastify API plugin with optional
* Swagger definitions.
*/
export async function generateOpenApiSpec(options: OpenApiGeneratorOptions) {
const fastify = Fastify().withTypeProvider<TypeBoxTypeProvider>();
await fastify.register(FastifySwagger, options.swaggerOptions);
await fastify.register(options.apiDefinition, { prefix: options.prefix });
await fastify.ready();

const directory = options.outputDirectory ?? './tmp';
if (!existsSync(directory)) mkdirSync(directory);
writeFileSync(`${directory}/openapi.yaml`, fastify.swagger({ yaml: true }));
writeFileSync(`${directory}/openapi.json`, JSON.stringify(fastify.swagger(), null, 2));

await fastify.close();
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './helpers';
export * from './logger';
export * from './fastify';
export * from './postgres';
export * from './server-version';
export * from './shutdown-handler';
2 changes: 2 additions & 0 deletions src/postgres/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { PG_TYPE_MAPPINGS } from './types';

/** Postgres client instance */
export type PgSqlClient = postgres.Sql<any> | postgres.TransactionSql<any>;
/** Postgres pending query or query fragment */
export type PgSqlQuery = postgres.PendingQuery<postgres.Row[]>;

/** Postgres connection URI string */
export type PgConnectionUri = string;
Expand Down