@platformatic/db 2.74.3 → 3.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config.d.ts +2 -30
- package/eslint.config.js +9 -5
- package/index.d.ts +56 -31
- package/index.js +67 -128
- package/lib/application.js +102 -0
- package/lib/commands/index.js +59 -0
- package/lib/commands/migrations-apply.js +62 -0
- package/lib/commands/migrations-create.js +48 -0
- package/lib/commands/print-schema.js +30 -0
- package/lib/commands/seed.js +72 -0
- package/lib/commands/types.js +21 -0
- package/lib/errors.js +15 -11
- package/lib/generator.js +229 -0
- package/lib/{migrator.mjs → migrator.js} +44 -37
- package/lib/{root-endpoint/index.js → root.js} +6 -7
- package/lib/schema.js +38 -22
- package/lib/stackable.js +14 -26
- package/lib/{generator/code-templates.js → templates.js} +57 -16
- package/lib/types.js +160 -0
- package/lib/upgrade.js +8 -12
- package/lib/utils.js +12 -23
- package/lib/versions/0.18.0.js +3 -5
- package/lib/versions/{from-zero-twenty-height-to-will-see.js → 0.28.0.js} +3 -5
- package/lib/versions/2.0.0.js +3 -5
- package/lib/versions/3.0.0.js +14 -0
- package/package.json +20 -28
- package/schema.json +9 -154
- package/tsconfig.json +16 -6
- package/.snapshots/810d795d512560f3863d8db472c81c27/0.json +0 -1
- package/.snapshots/810d795d512560f3863d8db472c81c27/1.json +0 -1
- package/db.mjs +0 -86
- package/help/compile.txt +0 -17
- package/help/create.txt +0 -13
- package/help/help.txt +0 -11
- package/help/migrations apply.txt +0 -45
- package/help/migrations create.txt +0 -27
- package/help/migrations.txt +0 -4
- package/help/schema.txt +0 -25
- package/help/seed.txt +0 -36
- package/help/start.txt +0 -47
- package/help/types.txt +0 -40
- package/index.test-d.ts +0 -43
- package/lib/adjust-config.js +0 -42
- package/lib/create.mjs +0 -89
- package/lib/gen-migration.mjs +0 -53
- package/lib/gen-schema.mjs +0 -68
- package/lib/gen-types.mjs +0 -202
- package/lib/generator/README.md +0 -38
- package/lib/generator/db-generator.js +0 -262
- package/lib/generator.d.ts +0 -7
- package/lib/migrate.mjs +0 -87
- package/lib/seed.mjs +0 -90
- /package/{lib/root-endpoint/public → public}/images/dark_mode.svg +0 -0
- /package/{lib/root-endpoint/public → public}/images/favicon.ico +0 -0
- /package/{lib/root-endpoint/public → public}/images/light_mode.svg +0 -0
- /package/{lib/root-endpoint/public → public}/images/platformatic-logo-dark.svg +0 -0
- /package/{lib/root-endpoint/public → public}/images/platformatic-logo-light.svg +0 -0
- /package/{lib/root-endpoint/public → public}/images/triangle_dark.svg +0 -0
- /package/{lib/root-endpoint/public → public}/images/triangle_light.svg +0 -0
- /package/{lib/root-endpoint/public → public}/index.html +0 -0
package/index.test-d.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { buildServer, PlatformaticApp, PlatformaticDBMixin, PlatformaticDBConfig, Entities, errors } from '.'
|
|
2
|
-
import ConfigManager from '@platformatic/config'
|
|
3
|
-
import type { Database } from '@platformatic/sql-mapper'
|
|
4
|
-
import { SQL } from '@databases/sql'
|
|
5
|
-
import { expectType } from 'tsd'
|
|
6
|
-
import { OpenAPI } from 'openapi-types'
|
|
7
|
-
import type { MercuriusPlugin } from 'mercurius'
|
|
8
|
-
import { FastifyError } from '@fastify/error'
|
|
9
|
-
|
|
10
|
-
declare module 'fastify' {
|
|
11
|
-
interface FastifyInstance {
|
|
12
|
-
platformatic: PlatformaticApp<PlatformaticDBConfig> & PlatformaticDBMixin<Entities>
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
async function main (): Promise<void> {
|
|
17
|
-
// TODO this configuration is incomplete, type it fully
|
|
18
|
-
const server = await buildServer({
|
|
19
|
-
server: {
|
|
20
|
-
port: 3042,
|
|
21
|
-
host: '127.0.0.1',
|
|
22
|
-
},
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
expectType<Database>(server.platformatic.db)
|
|
26
|
-
expectType<SQL>(server.platformatic.sql)
|
|
27
|
-
expectType<ConfigManager<PlatformaticDBConfig>>(server.platformatic.configManager)
|
|
28
|
-
expectType<PlatformaticDBConfig>(server.platformatic.config)
|
|
29
|
-
expectType<OpenAPI.Document>(server.swagger())
|
|
30
|
-
expectType<MercuriusPlugin>(server.graphql)
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
main().catch(console.error)
|
|
34
|
-
|
|
35
|
-
// Errors
|
|
36
|
-
type ErrorWithNoParams = () => FastifyError
|
|
37
|
-
type ErrorWithOneParam = (param: string) => FastifyError
|
|
38
|
-
|
|
39
|
-
expectType<ErrorWithNoParams>(errors.MigrateMissingMigrationsError)
|
|
40
|
-
expectType<ErrorWithNoParams>(errors.UnknownDatabaseError)
|
|
41
|
-
expectType<ErrorWithOneParam>(errors.MigrateMissingMigrationsDirError)
|
|
42
|
-
expectType<ErrorWithNoParams>(errors.MissingSeedFileError)
|
|
43
|
-
expectType<ErrorWithNoParams>(errors.MigrationsToApplyError)
|
package/lib/adjust-config.js
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
'use strict'
|
|
2
|
-
const { resolve } = require('path')
|
|
3
|
-
const { readFile } = require('fs/promises')
|
|
4
|
-
const { platformaticService } = require('@platformatic/service')
|
|
5
|
-
|
|
6
|
-
module.exports = async function adjustConfig (configManager) {
|
|
7
|
-
await platformaticService.configManagerConfig.transformConfig.call(configManager)
|
|
8
|
-
|
|
9
|
-
const dirOfConfig = configManager.dirname
|
|
10
|
-
if (configManager.current.db && configManager.current.db.connectionString.indexOf('sqlite') === 0 && configManager.current.db.connectionString !== 'sqlite://:memory:') {
|
|
11
|
-
const originalSqlitePath = configManager.current.db.connectionString.replace('sqlite://', '')
|
|
12
|
-
const sqliteFullPath = resolve(dirOfConfig, originalSqlitePath)
|
|
13
|
-
configManager.current.db.connectionString = 'sqlite://' + sqliteFullPath
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/* c8 ignore next 3 */
|
|
17
|
-
if (configManager.current.db.graphql?.schemaPath) {
|
|
18
|
-
configManager.current.db.graphql.schema = await readFile(configManager.current.db.graphql.schemaPath, 'utf8')
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/* c8 ignore next 2 */
|
|
22
|
-
const arePostgresqlSchemaDefined = configManager.current.db?.connectionString.indexOf('postgres') === 0 && configManager.current.db?.schema?.length > 0
|
|
23
|
-
const migrationsTableName = arePostgresqlSchemaDefined ? 'public.versions' : 'versions'
|
|
24
|
-
|
|
25
|
-
// relative-to-absolute migrations path
|
|
26
|
-
if (configManager.current.migrations) {
|
|
27
|
-
configManager.current.migrations.table = configManager.current.migrations.table || migrationsTableName
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
if (configManager.current.migrations && configManager.current.db) {
|
|
31
|
-
// TODO remove the ignores
|
|
32
|
-
/* c8 ignore next 4 */
|
|
33
|
-
configManager.current.db.ignore = configManager.current.db.ignore || {}
|
|
34
|
-
configManager.current.db.ignore = Object.assign({}, {
|
|
35
|
-
[configManager.current.migrations.table || migrationsTableName]: true,
|
|
36
|
-
}, configManager.current.db.ignore)
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (configManager.current.types?.autogenerate === 'true') {
|
|
40
|
-
configManager.current.types.autogenerate = true
|
|
41
|
-
}
|
|
42
|
-
}
|
package/lib/create.mjs
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
'use strict'
|
|
2
|
-
import minimist from 'minimist'
|
|
3
|
-
import { Generator } from '../lib/generator/db-generator.js'
|
|
4
|
-
import { join } from 'node:path'
|
|
5
|
-
import { getPkgManager } from '@platformatic/utils'
|
|
6
|
-
import { execa } from 'execa'
|
|
7
|
-
import ora from 'ora'
|
|
8
|
-
import { Table } from 'console-table-printer'
|
|
9
|
-
import pino from 'pino'
|
|
10
|
-
import pinoPretty from 'pino-pretty'
|
|
11
|
-
|
|
12
|
-
function printAppSummary (args, logger) {
|
|
13
|
-
logger.info('Creating a Platformatic DB app with this config: ')
|
|
14
|
-
const table = [
|
|
15
|
-
{ config: 'Directory', value: args.dir },
|
|
16
|
-
{ config: 'Connection String', value: args.connectionString },
|
|
17
|
-
{ config: 'Language', value: args.typescript ? 'Typescript' : 'Javascript' },
|
|
18
|
-
{ config: 'Init Git Repository', value: args.git },
|
|
19
|
-
{ config: 'Install Dependencies', value: args.install },
|
|
20
|
-
{ config: 'Sample Plugin and Tests', value: args.plugin },
|
|
21
|
-
{ config: 'Create Sample Migrations', value: args.migrations },
|
|
22
|
-
]
|
|
23
|
-
|
|
24
|
-
const p = new Table({
|
|
25
|
-
columns: [
|
|
26
|
-
{ name: 'config', alignment: 'right' },
|
|
27
|
-
{ name: 'value', alignment: 'left' },
|
|
28
|
-
],
|
|
29
|
-
})
|
|
30
|
-
|
|
31
|
-
p.addRows(table)
|
|
32
|
-
p.printTable()
|
|
33
|
-
}
|
|
34
|
-
async function createDB (_args) {
|
|
35
|
-
const stream = pinoPretty({
|
|
36
|
-
translateTime: 'SYS:HH:MM:ss',
|
|
37
|
-
ignore: 'hostname,pid',
|
|
38
|
-
minimumLevel: 'debug',
|
|
39
|
-
sync: true,
|
|
40
|
-
})
|
|
41
|
-
|
|
42
|
-
const logger = pino(stream)
|
|
43
|
-
|
|
44
|
-
const args = minimist(process.argv.slice(2), {
|
|
45
|
-
string: ['dir', 'port', 'hostname', 'connectionString'],
|
|
46
|
-
boolean: ['typescript', 'install', 'migrations', 'plugin', 'git'],
|
|
47
|
-
default: {
|
|
48
|
-
dir: join(process.cwd(), 'platformatic-db'),
|
|
49
|
-
port: 3042,
|
|
50
|
-
hostname: '0.0.0.0',
|
|
51
|
-
plugin: true,
|
|
52
|
-
typescript: false,
|
|
53
|
-
git: false,
|
|
54
|
-
install: true,
|
|
55
|
-
migrations: true,
|
|
56
|
-
connectionString: 'sqlite://./db.sqlite',
|
|
57
|
-
},
|
|
58
|
-
|
|
59
|
-
})
|
|
60
|
-
|
|
61
|
-
printAppSummary(args, logger)
|
|
62
|
-
|
|
63
|
-
const gen = new Generator({})
|
|
64
|
-
gen.setConfig({
|
|
65
|
-
port: args.port,
|
|
66
|
-
hostname: args.hostname,
|
|
67
|
-
plugin: args.plugin,
|
|
68
|
-
tests: args.plugin,
|
|
69
|
-
typescript: args.typescript,
|
|
70
|
-
initGitRepository: args.git,
|
|
71
|
-
targetDirectory: args.dir,
|
|
72
|
-
})
|
|
73
|
-
|
|
74
|
-
try {
|
|
75
|
-
await gen.run()
|
|
76
|
-
if (args.install) {
|
|
77
|
-
const pkgManager = getPkgManager()
|
|
78
|
-
const spinner = ora('Installing dependencies...').start()
|
|
79
|
-
await execa(pkgManager, ['install'], { cwd: args.dir })
|
|
80
|
-
spinner.succeed()
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
logger.info('Done! 🎉')
|
|
84
|
-
} catch (err) {
|
|
85
|
-
logger.error(err.message)
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export { createDB }
|
package/lib/gen-migration.mjs
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import { join } from 'path'
|
|
2
|
-
import { writeFile } from 'fs/promises'
|
|
3
|
-
import pino from 'pino'
|
|
4
|
-
import pretty from 'pino-pretty'
|
|
5
|
-
import { loadConfig } from '@platformatic/config'
|
|
6
|
-
import { Migrator } from './migrator.mjs'
|
|
7
|
-
import { platformaticDB } from '../index.js'
|
|
8
|
-
import errors from './errors.js'
|
|
9
|
-
|
|
10
|
-
async function generateMigration (_args) {
|
|
11
|
-
const logger = pino(pretty({
|
|
12
|
-
translateTime: 'SYS:HH:MM:ss',
|
|
13
|
-
ignore: 'hostname,pid',
|
|
14
|
-
}))
|
|
15
|
-
|
|
16
|
-
const { configManager } = await loadConfig({}, _args, platformaticDB)
|
|
17
|
-
await configManager.parseAndValidate()
|
|
18
|
-
const config = configManager.current
|
|
19
|
-
|
|
20
|
-
let migrator = null
|
|
21
|
-
try {
|
|
22
|
-
const migrationsConfig = config.migrations
|
|
23
|
-
if (migrationsConfig === undefined) {
|
|
24
|
-
throw new errors.MigrateMissingMigrationsError()
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
migrator = new Migrator(migrationsConfig, config.db, logger)
|
|
28
|
-
|
|
29
|
-
const nextMigrationVersion = await migrator.getNextMigrationVersion()
|
|
30
|
-
const nextMigrationVersionStr = migrator.convertVersionToStr(nextMigrationVersion)
|
|
31
|
-
|
|
32
|
-
const nextDoMigrationName = `${nextMigrationVersionStr}.do.sql`
|
|
33
|
-
const nextUndoMigrationName = `${nextMigrationVersionStr}.undo.sql`
|
|
34
|
-
|
|
35
|
-
const doFile = join(migrator.migrationDir, nextDoMigrationName)
|
|
36
|
-
const undoFile = join(migrator.migrationDir, nextUndoMigrationName)
|
|
37
|
-
|
|
38
|
-
await Promise.all([
|
|
39
|
-
writeFile(doFile, ''),
|
|
40
|
-
writeFile(undoFile, ''),
|
|
41
|
-
])
|
|
42
|
-
|
|
43
|
-
logger.info({ do: doFile, undo: undoFile }, 'Created migration files')
|
|
44
|
-
} catch (error) {
|
|
45
|
-
logger.error(error.message)
|
|
46
|
-
} finally {
|
|
47
|
-
if (migrator !== null) {
|
|
48
|
-
await migrator.close()
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export { generateMigration }
|
package/lib/gen-schema.mjs
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import pino from 'pino'
|
|
2
|
-
import pretty from 'pino-pretty'
|
|
3
|
-
import Fastify from 'fastify'
|
|
4
|
-
import graphql from 'graphql'
|
|
5
|
-
import { writeFile } from 'fs/promises'
|
|
6
|
-
import { loadConfig } from '@platformatic/config'
|
|
7
|
-
import { createServerConfig } from '@platformatic/utils'
|
|
8
|
-
import { platformaticDB } from '../index.js'
|
|
9
|
-
import { schema as platformaticDBschema } from './schema.js'
|
|
10
|
-
|
|
11
|
-
async function buildServer (_args, onServer) {
|
|
12
|
-
const logger = pino(pretty({
|
|
13
|
-
translateTime: 'SYS:HH:MM:ss',
|
|
14
|
-
ignore: 'hostname,pid',
|
|
15
|
-
minimumLevel: 'error',
|
|
16
|
-
}))
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
const { configManager } = await loadConfig({}, _args, platformaticDB)
|
|
20
|
-
|
|
21
|
-
await configManager.parseAndValidate()
|
|
22
|
-
const config = configManager.current
|
|
23
|
-
delete config.logger
|
|
24
|
-
config.loggerInstance = logger
|
|
25
|
-
|
|
26
|
-
const serverConfig = createServerConfig(config)
|
|
27
|
-
serverConfig.originalConfig = config
|
|
28
|
-
serverConfig.configManager = configManager
|
|
29
|
-
delete serverConfig.logger
|
|
30
|
-
serverConfig.loggerInstance = logger
|
|
31
|
-
|
|
32
|
-
const app = Fastify(serverConfig)
|
|
33
|
-
app.decorate('platformatic', { configManager, config: configManager.current })
|
|
34
|
-
app.register(platformaticDB, serverConfig)
|
|
35
|
-
|
|
36
|
-
await app.ready()
|
|
37
|
-
|
|
38
|
-
await onServer(app)
|
|
39
|
-
/* c8 ignore next 4 */
|
|
40
|
-
} catch (err) {
|
|
41
|
-
logger.error(err)
|
|
42
|
-
process.exit(1)
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function printGraphQLSchema (_args) {
|
|
47
|
-
buildServer(_args, async function (app) {
|
|
48
|
-
const schema = graphql.printSchema(app.graphql.schema)
|
|
49
|
-
console.log(schema)
|
|
50
|
-
await app.close()
|
|
51
|
-
})
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function printOpenAPISchema (_args) {
|
|
55
|
-
buildServer(_args, async function (app) {
|
|
56
|
-
const schema = app.swagger()
|
|
57
|
-
console.log(JSON.stringify(schema, null, 2))
|
|
58
|
-
await app.close()
|
|
59
|
-
})
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const filenameConfigJsonSchema = 'platformatic.db.schema.json'
|
|
63
|
-
|
|
64
|
-
async function generateJsonSchemaConfig () {
|
|
65
|
-
await writeFile(filenameConfigJsonSchema, JSON.stringify(platformaticDBschema, null, 2))
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export { printGraphQLSchema, printOpenAPISchema, generateJsonSchemaConfig, filenameConfigJsonSchema }
|
package/lib/gen-types.mjs
DELETED
|
@@ -1,202 +0,0 @@
|
|
|
1
|
-
import { loadConfig } from '@platformatic/config'
|
|
2
|
-
import { mapOpenAPItoTypes, mapSQLEntityToJSONSchema } from '@platformatic/sql-json-schema-mapper'
|
|
3
|
-
import utils, { createDirectory } from '@platformatic/utils'
|
|
4
|
-
import camelcase from 'camelcase'
|
|
5
|
-
import { readFile, readdir, unlink, writeFile } from 'fs/promises'
|
|
6
|
-
import { createRequire } from 'node:module'
|
|
7
|
-
import { basename, join, parse, posix, relative, resolve } from 'path'
|
|
8
|
-
import pino from 'pino'
|
|
9
|
-
import pretty from 'pino-pretty'
|
|
10
|
-
import { platformaticDB } from '../index.js'
|
|
11
|
-
import { isFileAccessible, setupDB } from './utils.js'
|
|
12
|
-
|
|
13
|
-
const checkForDependencies = utils.checkForDependencies
|
|
14
|
-
|
|
15
|
-
const GLOBAL_TYPES_TEMPLATE = `\
|
|
16
|
-
import type { PlatformaticApp, PlatformaticDBMixin, PlatformaticDBConfig, Entity, Entities, EntityHooks } from '@platformatic/db'
|
|
17
|
-
ENTITIES_IMPORTS_PLACEHOLDER
|
|
18
|
-
|
|
19
|
-
interface AppEntities extends Entities {
|
|
20
|
-
ENTITIES_DEFINITION_PLACEHOLDER
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
interface AppEntityHooks {
|
|
24
|
-
HOOKS_DEFINITION_PLACEHOLDER
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
declare module 'fastify' {
|
|
28
|
-
interface FastifyInstance {
|
|
29
|
-
platformatic: PlatformaticApp<PlatformaticDBConfig> &
|
|
30
|
-
PlatformaticDBMixin<AppEntities> &
|
|
31
|
-
AppEntityHooks
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
`
|
|
35
|
-
|
|
36
|
-
async function removeUnusedTypeFiles (entities, dir) {
|
|
37
|
-
const entityTypes = await readdir(dir)
|
|
38
|
-
const entityNames = Object.values(entities).map(entity => entity.name)
|
|
39
|
-
const removedEntityNames = entityTypes.filter(file => !entityNames.includes(basename(file, '.d.ts')))
|
|
40
|
-
await Promise.all(removedEntityNames.map(file => unlink(join(dir, file))))
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function getTypesFolderPath (cwd, config) {
|
|
44
|
-
return resolve(cwd, config.types?.dir ?? 'types')
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function generateEntityType (entity) {
|
|
48
|
-
const jsonSchema = mapSQLEntityToJSONSchema(entity)
|
|
49
|
-
const fieldDefinitions = Object.fromEntries(
|
|
50
|
-
Object.entries(entity.fields).map(([, value]) => [value.camelcase, value])
|
|
51
|
-
)
|
|
52
|
-
const tsCode = mapOpenAPItoTypes(jsonSchema, fieldDefinitions)
|
|
53
|
-
entity.name = camelcase(entity.name).replace(/^\w/, c => c.toUpperCase())
|
|
54
|
-
return tsCode + `\nexport { ${entity.name} };\n`
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function generateEntityGroupExport (entities) {
|
|
58
|
-
const completeTypesImports = []
|
|
59
|
-
const interfaceRows = []
|
|
60
|
-
for (const name of entities) {
|
|
61
|
-
completeTypesImports.push(`import { ${name} } from './${name}'`)
|
|
62
|
-
interfaceRows.push(`${name}: ${name}`)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const content = `${completeTypesImports.join('\n')}
|
|
66
|
-
|
|
67
|
-
interface EntityTypes {
|
|
68
|
-
${interfaceRows.join('\n ')}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export { EntityTypes, ${entities.join(', ')} }`
|
|
72
|
-
return content
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async function generateGlobalTypes (entities, config) {
|
|
76
|
-
const globalTypesImports = []
|
|
77
|
-
const globalTypesInterface = []
|
|
78
|
-
const globalHooks = []
|
|
79
|
-
const completeTypesImports = []
|
|
80
|
-
|
|
81
|
-
let typesRelativePath = relative(process.cwd(), getTypesFolderPath(process.cwd(), config))
|
|
82
|
-
{
|
|
83
|
-
const parsedPath = parse(typesRelativePath)
|
|
84
|
-
typesRelativePath = posix.format(parsedPath)
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const schemaIdTypes = []
|
|
88
|
-
const names = []
|
|
89
|
-
const keys = Object.keys(entities).sort()
|
|
90
|
-
for (const key of keys) {
|
|
91
|
-
const { name, singularName } = entities[key]
|
|
92
|
-
schemaIdTypes.push(name)
|
|
93
|
-
completeTypesImports.push(`import { ${name} } from './${typesRelativePath}/${name}'`)
|
|
94
|
-
globalTypesInterface.push(`${key}: Entity<${name}>,`)
|
|
95
|
-
globalHooks.push(`addEntityHooks(entityName: '${singularName}', hooks: EntityHooks<${name}>): any`)
|
|
96
|
-
names.push(name)
|
|
97
|
-
}
|
|
98
|
-
globalTypesImports.push(`import { EntityTypes, ${names.join(',')} } from './${typesRelativePath}'`)
|
|
99
|
-
|
|
100
|
-
const schemaIdType = schemaIdTypes.length === 0 ? 'string' : schemaIdTypes.map(type => `'${type}'`).join(' | ')
|
|
101
|
-
|
|
102
|
-
globalTypesImports.push(`
|
|
103
|
-
declare module 'fastify' {
|
|
104
|
-
interface FastifyInstance {
|
|
105
|
-
getSchema<T extends ${schemaIdType}>(schemaId: T): {
|
|
106
|
-
'$id': string,
|
|
107
|
-
title: string,
|
|
108
|
-
description: string,
|
|
109
|
-
type: string,
|
|
110
|
-
properties: {
|
|
111
|
-
[x in keyof EntityTypes[T]]: { type: string, nullable?: boolean }
|
|
112
|
-
},
|
|
113
|
-
required: string[]
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
}`)
|
|
117
|
-
|
|
118
|
-
return GLOBAL_TYPES_TEMPLATE.replace('ENTITIES_IMPORTS_PLACEHOLDER', globalTypesImports.join('\n'))
|
|
119
|
-
.replace('ENTITIES_DEFINITION_PLACEHOLDER', globalTypesInterface.join('\n '))
|
|
120
|
-
.replace('HOOKS_DEFINITION_PLACEHOLDER', globalHooks.join('\n '))
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async function writeFileIfChanged (filename, content) {
|
|
124
|
-
const isFileExists = await isFileAccessible(filename)
|
|
125
|
-
if (isFileExists) {
|
|
126
|
-
const fileContent = await readFile(filename, 'utf-8')
|
|
127
|
-
if (fileContent === content) return false
|
|
128
|
-
}
|
|
129
|
-
await writeFile(filename, content)
|
|
130
|
-
return true
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
async function execute ({ logger, config, configManager }) {
|
|
134
|
-
const wrap = await setupDB(logger, config.db)
|
|
135
|
-
const { db, entities } = wrap
|
|
136
|
-
if (Object.keys(entities).length === 0) {
|
|
137
|
-
// do not generate types if no schema is found
|
|
138
|
-
return 0
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const servicePath = configManager.dirname
|
|
142
|
-
const typesFolderPath = getTypesFolderPath(servicePath, config)
|
|
143
|
-
|
|
144
|
-
const isTypeFolderExists = await isFileAccessible(typesFolderPath)
|
|
145
|
-
if (isTypeFolderExists) {
|
|
146
|
-
await removeUnusedTypeFiles(entities, typesFolderPath)
|
|
147
|
-
} else {
|
|
148
|
-
await createDirectory(typesFolderPath)
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
let count = 0
|
|
152
|
-
const entitiesValues = Object.values(entities)
|
|
153
|
-
const entitiesNames = entitiesValues.map(({ name }) => name).sort()
|
|
154
|
-
for (const entity of entitiesValues) {
|
|
155
|
-
count++
|
|
156
|
-
const types = await generateEntityType(entity)
|
|
157
|
-
|
|
158
|
-
const pathToFile = join(typesFolderPath, entity.name + '.d.ts')
|
|
159
|
-
const isTypeChanged = await writeFileIfChanged(pathToFile, types)
|
|
160
|
-
|
|
161
|
-
if (isTypeChanged) {
|
|
162
|
-
logger.info(`Generated type for ${entity.name} entity.`)
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
const pathToFile = join(typesFolderPath, 'index.d.ts')
|
|
166
|
-
// maybe better to check here for changes
|
|
167
|
-
const content = await generateEntityGroupExport(entitiesNames)
|
|
168
|
-
const isTypeChanged = await writeFileIfChanged(pathToFile, content)
|
|
169
|
-
if (isTypeChanged) {
|
|
170
|
-
logger.info('Regenerating global.d.ts')
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const globalTypes = await generateGlobalTypes(entities, config)
|
|
174
|
-
const globalTypesFilePath = join(servicePath, 'global.d.ts')
|
|
175
|
-
await writeFileIfChanged(globalTypesFilePath, globalTypes)
|
|
176
|
-
|
|
177
|
-
await db.dispose()
|
|
178
|
-
return count
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
async function generateTypes (_args) {
|
|
182
|
-
const logger = pino(
|
|
183
|
-
pretty({
|
|
184
|
-
translateTime: 'SYS:HH:MM:ss',
|
|
185
|
-
ignore: 'hostname,pid'
|
|
186
|
-
})
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
const { configManager, args } = await loadConfig({}, _args, platformaticDB)
|
|
190
|
-
|
|
191
|
-
await configManager.parseAndValidate()
|
|
192
|
-
const config = configManager.current
|
|
193
|
-
|
|
194
|
-
const count = await execute({ logger, config, configManager })
|
|
195
|
-
if (count === 0) {
|
|
196
|
-
logger.warn('No entities found in your schema. Types were NOT generated.')
|
|
197
|
-
logger.warn('Please run `platformatic db migrations apply` to generate types.')
|
|
198
|
-
}
|
|
199
|
-
await checkForDependencies(logger, args, createRequire(import.meta.url), config, ['@platformatic/db'])
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export { execute, generateTypes }
|
package/lib/generator/README.md
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
# Platformatic DB API
|
|
2
|
-
|
|
3
|
-
This is a generated [Platformatic DB](https://docs.platformatic.dev/docs/db/overview) application.
|
|
4
|
-
|
|
5
|
-
## Requirements
|
|
6
|
-
|
|
7
|
-
Platformatic supports macOS, Linux and Windows ([WSL](https://docs.microsoft.com/windows/wsl/) recommended).
|
|
8
|
-
You'll need to have [Node.js](https://nodejs.org/) >= v18.8.0 or >= v20.6.0
|
|
9
|
-
|
|
10
|
-
## Setup
|
|
11
|
-
|
|
12
|
-
1. Install dependencies:
|
|
13
|
-
|
|
14
|
-
```bash
|
|
15
|
-
npm install
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
2. Apply migrations:
|
|
19
|
-
|
|
20
|
-
```bash
|
|
21
|
-
npm run migrate
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
## Usage
|
|
26
|
-
|
|
27
|
-
Run the API with:
|
|
28
|
-
|
|
29
|
-
```bash
|
|
30
|
-
npm start
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
### Explore
|
|
34
|
-
- ⚡ The Platformatic DB server is running at http://localhost:3042/
|
|
35
|
-
- 📔 View the REST API's Swagger documentation at http://localhost:3042/documentation/
|
|
36
|
-
- 🔍 Try out the GraphiQL web UI at http://localhost:3042/graphiql
|
|
37
|
-
|
|
38
|
-
|