-
-
Notifications
You must be signed in to change notification settings - Fork 140
feat: add typescript typegen endpoint #269
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import type { FastifyInstance } from 'fastify' | ||
import { PostgresMeta } from '../../../lib' | ||
import { DEFAULT_POOL_CONFIG } from '../../constants' | ||
import { extractRequestForLogging } from '../../utils' | ||
import { apply as applyTypescriptTemplate } from '../../templates/typescript' | ||
|
||
export default async (fastify: FastifyInstance) => { | ||
fastify.get<{ | ||
Headers: { pg: string } | ||
Querystring: { | ||
excluded_schemas?: string | ||
} | ||
}>('/', async (request, reply) => { | ||
const connectionString = request.headers.pg | ||
const excludedSchemas = | ||
request.query.excluded_schemas?.split(',').map((schema) => schema.trim()) ?? [] | ||
|
||
const pgMeta: PostgresMeta = new PostgresMeta({ ...DEFAULT_POOL_CONFIG, connectionString }) | ||
const { data: schemas, error: schemasError } = await pgMeta.schemas.list() | ||
const { data: tables, error: tablesError } = await pgMeta.tables.list() | ||
const { data: functions, error: functionsError } = await pgMeta.functions.list() | ||
const { data: types, error: typesError } = await pgMeta.types.list({ | ||
includeSystemSchemas: true, | ||
}) | ||
await pgMeta.end() | ||
|
||
if (schemasError) { | ||
request.log.error({ error: schemasError, request: extractRequestForLogging(request) }) | ||
reply.code(500) | ||
return { error: schemasError.message } | ||
} | ||
if (tablesError) { | ||
request.log.error({ error: tablesError, request: extractRequestForLogging(request) }) | ||
reply.code(500) | ||
return { error: tablesError.message } | ||
} | ||
if (functionsError) { | ||
request.log.error({ error: functionsError, request: extractRequestForLogging(request) }) | ||
reply.code(500) | ||
return { error: functionsError.message } | ||
} | ||
if (typesError) { | ||
request.log.error({ error: typesError, request: extractRequestForLogging(request) }) | ||
reply.code(500) | ||
return { error: typesError.message } | ||
} | ||
|
||
return applyTypescriptTemplate({ | ||
schemas: schemas.filter(({ name }) => !excludedSchemas.includes(name)), | ||
tables, | ||
functions, | ||
types, | ||
}) | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
import prettier from 'prettier' | ||
import type { PostgresFunction, PostgresSchema, PostgresTable, PostgresType } from '../../lib' | ||
|
||
export const apply = ({ | ||
schemas, | ||
tables, | ||
functions, | ||
types, | ||
}: { | ||
schemas: PostgresSchema[] | ||
tables: PostgresTable[] | ||
functions: PostgresFunction[] | ||
types: PostgresType[] | ||
}): string => { | ||
let output = ` | ||
export type Json = string | number | boolean | null | { [key: string]: Json } | Json[] | ||
|
||
export interface Database { | ||
${schemas.map( | ||
(schema) => | ||
`${JSON.stringify(schema.name)}: { | ||
Tables: { | ||
${tables | ||
.filter((table) => table.schema === schema.name) | ||
.map( | ||
(table) => `${JSON.stringify(table.name)}: { | ||
Row: { | ||
${table.columns.map( | ||
(column) => | ||
`${JSON.stringify(column.name)}: ${pgTypeToTsType(column.format, types)} ${ | ||
column.is_nullable ? '| null' : '' | ||
}` | ||
)} | ||
} | ||
Insert: { | ||
${table.columns.map((column) => { | ||
let output = JSON.stringify(column.name) | ||
|
||
if (column.identity_generation === 'ALWAYS') { | ||
return `${output}?: never` | ||
} | ||
|
||
if ( | ||
column.is_nullable || | ||
column.is_identity || | ||
column.default_value !== null | ||
) { | ||
output += '?:' | ||
} else { | ||
output += ':' | ||
} | ||
|
||
output += pgTypeToTsType(column.format, types) | ||
|
||
if (column.is_nullable) { | ||
output += '| null' | ||
} | ||
|
||
return output | ||
})} | ||
} | ||
Update: { | ||
${table.columns.map((column) => { | ||
let output = JSON.stringify(column.name) | ||
|
||
if (column.identity_generation === 'ALWAYS') { | ||
return `${output}?: never` | ||
} | ||
|
||
output += `?: ${pgTypeToTsType(column.format, types)}` | ||
|
||
if (column.is_nullable) { | ||
output += '| null' | ||
} | ||
|
||
return output | ||
})} | ||
} | ||
}` | ||
)} | ||
} | ||
Functions: { | ||
${functions | ||
.filter( | ||
(function_) => | ||
function_.schema === schema.name && function_.return_type !== 'trigger' | ||
) | ||
.map( | ||
(function_) => `${JSON.stringify(function_.name)}: { | ||
Args: ${(() => { | ||
if (function_.argument_types === '') { | ||
return 'Record<PropertyKey, never>' | ||
} | ||
|
||
const splitArgs = function_.argument_types.split(',').map((arg) => arg.trim()) | ||
if (splitArgs.some((arg) => arg.includes('"') || !arg.includes(' '))) { | ||
return 'Record<string, unknown>' | ||
} | ||
|
||
const argsNameAndType = splitArgs.map((arg) => { | ||
const [name, ...rest] = arg.split(' ') | ||
const type = types.find((_type) => _type.format === rest.join(' ')) | ||
if (!type) { | ||
return { name, type: 'unknown' } | ||
} | ||
return { name, type: pgTypeToTsType(type.name, types) } | ||
}) | ||
|
||
return `{ ${argsNameAndType.map( | ||
({ name, type }) => `${JSON.stringify(name)}: ${type}` | ||
)} }` | ||
})()} | ||
Returns: ${pgTypeToTsType(function_.return_type, types)} | ||
}` | ||
)} | ||
} | ||
}` | ||
)} | ||
}` | ||
|
||
output = prettier.format(output, { | ||
parser: 'typescript', | ||
}) | ||
return output | ||
} | ||
|
||
// TODO: Make this more robust. Currently doesn't handle composite types - returns them as unknown. | ||
const pgTypeToTsType = (pgType: string, types: PostgresType[]): string => { | ||
if (pgType === 'bool') { | ||
return 'boolean' | ||
} else if (['int2', 'int4', 'int8', 'float4', 'float8', 'numeric'].includes(pgType)) { | ||
return 'number' | ||
} else if ( | ||
[ | ||
'bytea', | ||
'bpchar', | ||
'varchar', | ||
'date', | ||
'text', | ||
'time', | ||
'timetz', | ||
'timestamp', | ||
'timestamptz', | ||
'uuid', | ||
].includes(pgType) | ||
) { | ||
return 'string' | ||
} else if (['json', 'jsonb'].includes(pgType)) { | ||
return 'Json' | ||
} else if (pgType === 'void') { | ||
return 'undefined' | ||
} else if (pgType === 'record') { | ||
return 'Record<string, unknown>[]' | ||
} else if (pgType.startsWith('_')) { | ||
return pgTypeToTsType(pgType.substring(1), types) + '[]' | ||
} else { | ||
const type = types.find((type) => type.name === pgType && type.enums.length > 0) | ||
if (type) { | ||
return type.enums.map((variant) => JSON.stringify(variant)).join('|') | ||
} | ||
|
||
return 'unknown' | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is for
auth
,storage
,graphql
,realtime
etc. - we should only generate for user's schemas