|
| 1 | +import { isDataSource } from '@zenstackhq/language/ast'; |
| 2 | +import { getOutputPath, getSchemaFile, loadSchemaDocument } from './action-utils'; |
| 3 | +import { CliError } from '../cli-error'; |
| 4 | +import { ZModelCodeGenerator } from '@zenstackhq/language'; |
| 5 | +import { getStringLiteral } from '@zenstackhq/language/utils'; |
| 6 | +import { SqliteDialect } from '@zenstackhq/orm/dialects/sqlite'; |
| 7 | +import { PostgresDialect } from '@zenstackhq/orm/dialects/postgres'; |
| 8 | +import SQLite from 'better-sqlite3'; |
| 9 | +import { Pool } from 'pg'; |
| 10 | +import path from 'node:path'; |
| 11 | +import { ZenStackClient, type ClientContract } from '@zenstackhq/orm'; |
| 12 | +import { RPCApiHandler } from '@zenstackhq/server/api'; |
| 13 | +import { ZenStackMiddleware } from '@zenstackhq/server/express'; |
| 14 | +import express from 'express'; |
| 15 | +import colors from 'colors'; |
| 16 | +import { createJiti } from 'jiti'; |
| 17 | +import { getVersion } from '../utils/version-utils'; |
| 18 | +import cors from 'cors'; |
| 19 | + |
| 20 | +type Options = { |
| 21 | + output?: string; |
| 22 | + schema?: string; |
| 23 | + port?: number; |
| 24 | + logLevel?: string[]; |
| 25 | + databaseUrl?: string; |
| 26 | +}; |
| 27 | + |
| 28 | +export async function run(options: Options) { |
| 29 | + const schemaFile = getSchemaFile(options.schema); |
| 30 | + console.log(colors.gray(`Loading ZModel schema from: ${schemaFile}`)); |
| 31 | + |
| 32 | + let outputPath = getOutputPath(options, schemaFile); |
| 33 | + |
| 34 | + // Ensure outputPath is absolute |
| 35 | + if (!path.isAbsolute(outputPath)) { |
| 36 | + outputPath = path.resolve(process.cwd(), outputPath); |
| 37 | + } |
| 38 | + |
| 39 | + const model = await loadSchemaDocument(schemaFile); |
| 40 | + |
| 41 | + const dataSource = model.declarations.find(isDataSource); |
| 42 | + |
| 43 | + let databaseUrl = options.databaseUrl; |
| 44 | + |
| 45 | + if (!databaseUrl) { |
| 46 | + const schemaUrl = dataSource?.fields.find((f) => f.name === 'url')?.value; |
| 47 | + |
| 48 | + if (!schemaUrl) { |
| 49 | + throw new CliError( |
| 50 | + `The schema's "datasource" does not have a "url" field, please provide it with -d option.`, |
| 51 | + ); |
| 52 | + } |
| 53 | + const zModelGenerator = new ZModelCodeGenerator(); |
| 54 | + const url = zModelGenerator.generate(schemaUrl); |
| 55 | + |
| 56 | + databaseUrl = evaluateUrl(url); |
| 57 | + } |
| 58 | + |
| 59 | + const provider = getStringLiteral(dataSource?.fields.find((f) => f.name === 'provider')?.value)!; |
| 60 | + |
| 61 | + const dialect = createDialect(provider, databaseUrl!, outputPath); |
| 62 | + |
| 63 | + const jiti = createJiti(import.meta.url); |
| 64 | + |
| 65 | + const schemaModule = (await jiti.import(path.join(outputPath, 'schema'))) as any; |
| 66 | + |
| 67 | + const allowedLogLevels = ['error', 'query'] as const; |
| 68 | + const log = options.logLevel?.filter((level): level is (typeof allowedLogLevels)[number] => |
| 69 | + allowedLogLevels.includes(level as any), |
| 70 | + ); |
| 71 | + |
| 72 | + const db = new ZenStackClient(schemaModule.schema, { |
| 73 | + dialect: dialect, |
| 74 | + log: log && log.length > 0 ? log : undefined, |
| 75 | + }); |
| 76 | + |
| 77 | + // check whether the database is reachable |
| 78 | + try { |
| 79 | + await db.$connect(); |
| 80 | + } catch (err) { |
| 81 | + throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`); |
| 82 | + } |
| 83 | + |
| 84 | + startServer(db, schemaModule.schema, options); |
| 85 | +} |
| 86 | + |
| 87 | +function evaluateUrl(value: string): string { |
| 88 | + // Create env helper function |
| 89 | + const env = (varName: string) => { |
| 90 | + const envValue = process.env[varName]; |
| 91 | + if (!envValue) { |
| 92 | + throw new CliError(`Environment variable ${varName} is not set`); |
| 93 | + } |
| 94 | + return envValue; |
| 95 | + }; |
| 96 | + |
| 97 | + try { |
| 98 | + // Use Function constructor to evaluate the url value |
| 99 | + const urlFn = new Function('env', `return ${value}`); |
| 100 | + const url = urlFn(env); |
| 101 | + return url; |
| 102 | + } catch (err) { |
| 103 | + if (err instanceof CliError) { |
| 104 | + throw err; |
| 105 | + } |
| 106 | + throw new CliError('Could not evaluate datasource url from schema, you could provide it via -d option.'); |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +function createDialect(provider: string, databaseUrl: string, outputPath: string) { |
| 111 | + switch (provider) { |
| 112 | + case 'sqlite': { |
| 113 | + let resolvedUrl = databaseUrl.trim(); |
| 114 | + if (resolvedUrl.startsWith('file:')) { |
| 115 | + const filePath = resolvedUrl.substring('file:'.length); |
| 116 | + if (!path.isAbsolute(filePath)) { |
| 117 | + resolvedUrl = path.join(outputPath, filePath); |
| 118 | + } |
| 119 | + } |
| 120 | + console.log(colors.gray(`Connecting to SQLite database at: ${resolvedUrl}`)); |
| 121 | + return new SqliteDialect({ |
| 122 | + database: new SQLite(resolvedUrl), |
| 123 | + }); |
| 124 | + } |
| 125 | + case 'postgresql': |
| 126 | + console.log(colors.gray(`Connecting to PostgreSQL database at: ${databaseUrl}`)); |
| 127 | + return new PostgresDialect({ |
| 128 | + pool: new Pool({ |
| 129 | + connectionString: databaseUrl, |
| 130 | + }), |
| 131 | + }); |
| 132 | + default: |
| 133 | + throw new CliError(`Unsupported database provider: ${provider}`); |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +function startServer(client: ClientContract<any, any>, schema: any, options: Options) { |
| 138 | + const app = express(); |
| 139 | + app.use(cors()); |
| 140 | + app.use(express.json({ limit: '5mb' })); |
| 141 | + app.use(express.urlencoded({ extended: true, limit: '5mb' })); |
| 142 | + |
| 143 | + app.use( |
| 144 | + '/api/model', |
| 145 | + ZenStackMiddleware({ |
| 146 | + apiHandler: new RPCApiHandler({ schema }), |
| 147 | + getClient: () => client, |
| 148 | + }), |
| 149 | + ); |
| 150 | + |
| 151 | + app.get('/api/schema', (_req, res: express.Response) => { |
| 152 | + res.json({ ...schema, zenstackVersion: getVersion() }); |
| 153 | + }); |
| 154 | + |
| 155 | + const server = app.listen(options.port, () => { |
| 156 | + console.log(`ZenStack proxy server is running on port: ${options.port}`); |
| 157 | + console.log(`You can visit ZenStack Studio at: ${colors.blue('https://studio.zenstack.dev')}`); |
| 158 | + }); |
| 159 | + |
| 160 | + // Graceful shutdown |
| 161 | + process.on('SIGTERM', async () => { |
| 162 | + server.close(() => { |
| 163 | + console.log('\nZenStack proxy server closed'); |
| 164 | + }); |
| 165 | + |
| 166 | + await client.$disconnect(); |
| 167 | + process.exit(0); |
| 168 | + }); |
| 169 | + |
| 170 | + process.on('SIGINT', async () => { |
| 171 | + server.close(() => { |
| 172 | + console.log('\nZenStack proxy server closed'); |
| 173 | + }); |
| 174 | + await client.$disconnect(); |
| 175 | + process.exit(0); |
| 176 | + }); |
| 177 | +} |
0 commit comments