/* eslint-disable no-console */ import { JSONPgSmartTags } from 'graphile-utils'; import * as path from 'path'; import { exitCode } from '../../common'; import { ContentEntityModel } from './content-entity-model'; import { getContentMetadataSchemas } from './pg-models/json-schema-parse-utils'; import { generateMigration } from './pg-models/pg-sql-gen-utils'; import { generateSmartTagsPlugin } from './pg-models/pgl-utils'; import { collectionPostprocessor, ContentEntityModelPostprocessor, episodePostprocessor, moviePostprocessor, seasonPostprocessor, tvshowPostprocessor, } from './postprocessors'; import { PublishSchemaToDbOptions } from './publish-schema-to-db-options'; /** * Generates a database schema from an asset publish format JSON schema. */ export async function generate( options: PublishSchemaToDbOptions, ): Promise { console.log(`Searching for schemas matching pattern ${options.inputGlob}`); try { // 1. Read all publish events. const contentTypeSchemas = await getContentMetadataSchemas( options.inputGlob, ); const modelPostProcessors: { [name: string]: ContentEntityModelPostprocessor; } = { movie: moviePostprocessor, tvshow: tvshowPostprocessor, season: seasonPostprocessor, episode: episodePostprocessor, collection: collectionPostprocessor, }; const contentEntityModels: ContentEntityModel[] = []; const statements: string[] = []; const smartTags: JSONPgSmartTags = { version: 1, config: { class: {}, }, }; for (const contentTypeSchema of contentTypeSchemas) { contentEntityModels.push( new ContentEntityModel(options, contentTypeSchema), ); } for (const model of contentEntityModels) { const otherModels = contentEntityModels.filter( (m) => m.contentEntity.name !== model.contentEntity.name, ); const postprocess = modelPostProcessors[model.contentEntity.name]; if (postprocess !== undefined) { console.log( `Found model postprocessor for ${model.contentEntity.name}.`, ); postprocess(model, otherModels, options); } model.validate(); smartTags.config.class = { ...smartTags.config.class, ...model.buildSmartTags(), }; statements.push(...model.buildStatements()); } // 3. Generate SQL. await generateMigration( statements, path.join(options.outputRoot, 'migrations', 'current.sql'), ); generateSmartTagsPlugin( smartTags, path.join(options.outputRoot, 'src', 'plugins', 'smart-tags-plugin.ts'), ); } catch (e) { console.log(e); process.exit(exitCode); } }