Skip to content

Commit 5e4c87f

Browse files
committed
refactor: extract buildApp into its own file
1 parent 618b2bf commit 5e4c87f

File tree

5 files changed

+122
-122
lines changed

5 files changed

+122
-122
lines changed

.pkg.config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@supabase/postgres-meta",
33
"bin": {
4-
"postgres-meta": "dist/server/app.js"
4+
"postgres-meta": "dist/server/server.js"
55
},
66
"pkg": {
77
"outputPath": "bin",

package.json

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@
2121
"clean": "rimraf dist tsconfig.tsbuildinfo",
2222
"format": "prettier --write \"{src,test}/**/*.ts\"",
2323
"build": "tsc -p tsconfig.json && cpy 'src/lib/sql/*.sql' dist/lib/sql",
24-
"docs:export": "node --loader ts-node/esm src/server/app.ts docs export > openapi.json",
25-
"gen:types:typescript": "node --loader ts-node/esm src/server/app.ts gen types typescript",
26-
"start": "node dist/server/app.js",
27-
"dev": "trap 'npm run db:clean' INT && run-s db:clean db:run && nodemon --exec node --loader ts-node/esm src/server/app.ts | pino-pretty --colorize",
24+
"docs:export": "node --loader ts-node/esm src/server/server.ts docs export > openapi.json",
25+
"gen:types:typescript": "node --loader ts-node/esm src/server/server.ts gen types typescript",
26+
"start": "node dist/server/server.js",
27+
"dev": "trap 'npm run db:clean' INT && run-s db:clean db:run && nodemon --exec node --loader ts-node/esm src/server/server.ts | pino-pretty --colorize",
2828
"pkg": "run-s clean build && pkg .pkg.config.json",
2929
"test": "run-s db:clean db:run test:run db:clean",
3030
"db:clean": "cd test/db && docker-compose down",

src/lib/index.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import PostgresMeta from './PostgresMeta.js'
2-
export { PostgresMeta }
1+
export { default as PostgresMeta } from './PostgresMeta.js'
32
export {
43
PostgresMetaOk,
54
PostgresMetaErr,

src/server/app.ts

Lines changed: 30 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,29 @@
1-
import swagger from '@fastify/swagger'
21
import cors from '@fastify/cors'
3-
import { fastify } from 'fastify'
4-
import { pino } from 'pino'
5-
import { PostgresMeta } from '../lib/index.js'
6-
import {
7-
DEFAULT_POOL_CONFIG,
8-
EXPORT_DOCS,
9-
GENERATE_TYPES,
10-
GENERATE_TYPES_INCLUDED_SCHEMAS,
11-
PG_CONNECTION,
12-
PG_META_HOST,
13-
PG_META_PORT,
14-
PG_META_REQ_HEADER,
15-
} from './constants.js'
2+
import swagger from '@fastify/swagger'
3+
import { fastify, FastifyInstance, FastifyServerOptions } from 'fastify'
4+
import { PG_META_REQ_HEADER } from './constants.js'
165
import routes from './routes/index.js'
17-
import { apply as applyTypescriptTemplate } from './templates/typescript.js'
186
import { extractRequestForLogging } from './utils.js'
19-
import { build as buildAdminApp } from './admin-app.js'
207
// Pseudo package declared only for this module
218
import pkg from '#package.json' assert { type: 'json' }
229

23-
const logger = pino({
24-
formatters: {
25-
level(label) {
26-
return { level: label }
27-
},
28-
},
29-
timestamp: pino.stdTimeFunctions.isoTime,
30-
})
31-
32-
const app = fastify({
33-
logger,
34-
disableRequestLogging: true,
35-
requestIdHeader: PG_META_REQ_HEADER,
36-
})
10+
export const build = (opts: FastifyServerOptions = {}): FastifyInstance => {
11+
const app = fastify({
12+
disableRequestLogging: true,
13+
requestIdHeader: PG_META_REQ_HEADER,
14+
...opts,
15+
})
3716

38-
app.setErrorHandler((error, request, reply) => {
39-
app.log.error({ error: error.toString(), request: extractRequestForLogging(request) })
40-
reply.code(500).send({ error: error.message })
41-
})
17+
app.setErrorHandler((error, request, reply) => {
18+
app.log.error({ error: error.toString(), request: extractRequestForLogging(request) })
19+
reply.code(500).send({ error: error.message })
20+
})
4221

43-
app.setNotFoundHandler((request, reply) => {
44-
app.log.error({ error: 'Not found', request: extractRequestForLogging(request) })
45-
reply.code(404).send({ error: 'Not found' })
46-
})
22+
app.setNotFoundHandler((request, reply) => {
23+
app.log.error({ error: 'Not found', request: extractRequestForLogging(request) })
24+
reply.code(404).send({ error: 'Not found' })
25+
})
4726

48-
if (EXPORT_DOCS) {
4927
app.register(swagger, {
5028
openapi: {
5129
servers: [],
@@ -57,85 +35,22 @@ if (EXPORT_DOCS) {
5735
},
5836
})
5937

60-
app.ready(() => {
61-
// @ts-ignore: app.swagger() is a Fastify decorator, so doesn't show up in the types
62-
console.log(JSON.stringify(app.swagger(), null, 2))
63-
})
64-
} else if (GENERATE_TYPES === 'typescript') {
65-
;(async () => {
66-
const pgMeta: PostgresMeta = new PostgresMeta({
67-
...DEFAULT_POOL_CONFIG,
68-
connectionString: PG_CONNECTION,
69-
})
70-
const { data: schemas, error: schemasError } = await pgMeta.schemas.list()
71-
const { data: tables, error: tablesError } = await pgMeta.tables.list()
72-
const { data: views, error: viewsError } = await pgMeta.views.list()
73-
const { data: functions, error: functionsError } = await pgMeta.functions.list()
74-
const { data: types, error: typesError } = await pgMeta.types.list({
75-
includeArrayTypes: true,
76-
includeSystemSchemas: true,
77-
})
78-
await pgMeta.end()
38+
app.register(cors)
7939

80-
if (schemasError) {
81-
throw new Error(schemasError.message)
82-
}
83-
if (tablesError) {
84-
throw new Error(tablesError.message)
40+
app.get('/', async (_request, _reply) => {
41+
return {
42+
status: 200,
43+
name: pkg.name,
44+
version: pkg.version,
45+
documentation: 'https://github.com/supabase/postgres-meta',
8546
}
86-
if (viewsError) {
87-
throw new Error(viewsError.message)
88-
}
89-
if (functionsError) {
90-
throw new Error(functionsError.message)
91-
}
92-
if (typesError) {
93-
throw new Error(typesError.message)
94-
}
95-
96-
console.log(
97-
applyTypescriptTemplate({
98-
schemas: schemas.filter(
99-
({ name }) =>
100-
GENERATE_TYPES_INCLUDED_SCHEMAS.length === 0 ||
101-
GENERATE_TYPES_INCLUDED_SCHEMAS.includes(name)
102-
),
103-
tables,
104-
views,
105-
functions: functions.filter(
106-
({ return_type }) => !['trigger', 'event_trigger'].includes(return_type)
107-
),
108-
types: types.filter(({ name }) => name[0] !== '_'),
109-
arrayTypes: types.filter(({ name }) => name[0] === '_'),
110-
})
111-
)
112-
})()
113-
} else {
114-
app.ready(() => {
115-
app.listen({ port: PG_META_PORT, host: PG_META_HOST }, () => {
116-
app.log.info(`App started on port ${PG_META_PORT}`)
117-
const adminApp = buildAdminApp({ logger })
118-
const adminPort = PG_META_PORT + 1
119-
adminApp.listen({ port: adminPort, host: PG_META_HOST }, () => {
120-
adminApp.log.info(`Admin App started on port ${adminPort}`)
121-
})
122-
})
12347
})
124-
}
125-
126-
app.register(cors)
12748

128-
app.get('/', async (_request, _reply) => {
129-
return {
130-
status: 200,
131-
name: pkg.name,
132-
version: pkg.version,
133-
documentation: 'https://github.com/supabase/postgres-meta',
134-
}
135-
})
49+
app.get('/health', async (_request, _reply) => {
50+
return { date: new Date() }
51+
})
13652

137-
app.get('/health', async (_request, _reply) => {
138-
return { date: new Date() }
139-
})
53+
app.register(routes)
14054

141-
app.register(routes)
55+
return app
56+
}

src/server/server.ts

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { pino } from 'pino'
2+
import { PostgresMeta } from '../lib/index.js'
3+
import { build as buildApp } from './app.js'
4+
import { build as buildAdminApp } from './admin-app.js'
5+
import {
6+
DEFAULT_POOL_CONFIG,
7+
EXPORT_DOCS,
8+
GENERATE_TYPES,
9+
GENERATE_TYPES_INCLUDED_SCHEMAS,
10+
PG_CONNECTION,
11+
PG_META_HOST,
12+
PG_META_PORT,
13+
} from './constants.js'
14+
import { apply as applyTypescriptTemplate } from './templates/typescript.js'
15+
16+
const logger = pino({
17+
formatters: {
18+
level(label) {
19+
return { level: label }
20+
},
21+
},
22+
timestamp: pino.stdTimeFunctions.isoTime,
23+
})
24+
25+
const app = buildApp({ logger })
26+
const adminApp = buildAdminApp({ logger })
27+
28+
if (EXPORT_DOCS) {
29+
// TODO: Move to a separate script.
30+
await app.ready()
31+
// @ts-ignore: app.swagger() is a Fastify decorator, so doesn't show up in the types
32+
console.log(JSON.stringify(app.swagger(), null, 2))
33+
} else if (GENERATE_TYPES === 'typescript') {
34+
// TODO: Move to a separate script.
35+
const pgMeta: PostgresMeta = new PostgresMeta({
36+
...DEFAULT_POOL_CONFIG,
37+
connectionString: PG_CONNECTION,
38+
})
39+
const { data: schemas, error: schemasError } = await pgMeta.schemas.list()
40+
const { data: tables, error: tablesError } = await pgMeta.tables.list()
41+
const { data: views, error: viewsError } = await pgMeta.views.list()
42+
const { data: functions, error: functionsError } = await pgMeta.functions.list()
43+
const { data: types, error: typesError } = await pgMeta.types.list({
44+
includeArrayTypes: true,
45+
includeSystemSchemas: true,
46+
})
47+
await pgMeta.end()
48+
49+
if (schemasError) {
50+
throw new Error(schemasError.message)
51+
}
52+
if (tablesError) {
53+
throw new Error(tablesError.message)
54+
}
55+
if (viewsError) {
56+
throw new Error(viewsError.message)
57+
}
58+
if (functionsError) {
59+
throw new Error(functionsError.message)
60+
}
61+
if (typesError) {
62+
throw new Error(typesError.message)
63+
}
64+
65+
console.log(
66+
applyTypescriptTemplate({
67+
schemas: schemas.filter(
68+
({ name }) =>
69+
GENERATE_TYPES_INCLUDED_SCHEMAS.length === 0 ||
70+
GENERATE_TYPES_INCLUDED_SCHEMAS.includes(name)
71+
),
72+
tables,
73+
views,
74+
functions: functions.filter(
75+
({ return_type }) => !['trigger', 'event_trigger'].includes(return_type)
76+
),
77+
types: types.filter(({ name }) => name[0] !== '_'),
78+
arrayTypes: types.filter(({ name }) => name[0] === '_'),
79+
})
80+
)
81+
} else {
82+
app.listen({ port: PG_META_PORT, host: PG_META_HOST }, () => {
83+
const adminPort = PG_META_PORT + 1
84+
adminApp.listen({ port: adminPort, host: PG_META_HOST })
85+
})
86+
}

0 commit comments

Comments
 (0)