Skip to content

Commit

Permalink
feat((synced-files)): sync type files when directus starts
Browse files Browse the repository at this point in the history
Also adds a disclaimer to the generated types files

maltejur#27
  • Loading branch information
jclaveau committed Jul 8, 2023
1 parent 1a0a076 commit 545bc53
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions src/extension-hook.sync-ts-files/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { Collections } from '../lib/types';
import { gatherCollectionsData } from '../lib/generate-types/utils';
import * as fs from 'node:fs';

export default defineHook(({ action }, extCtx) => {
const { services: { CollectionsService, FieldsService, RelationsService }, env, logger } = extCtx;
export default defineHook(async ({ action }, extCtx) => {
const { services: { CollectionsService, FieldsService, RelationsService }, env, logger, getSchema } = extCtx;

let targetFiles: string | string[] = env.GENERATE_TYPES_SYNCED_TS_FILES;

Expand All @@ -19,7 +19,9 @@ export default defineHook(({ action }, extCtx) => {
targetFiles = [targetFiles]
}

const listCollections = async (schema: SchemaOverview) => {

const saveTypescriptTypesToFile = async () => {
const schema: SchemaOverview = await getSchema();
const collectionsService = new CollectionsService({schema});
const collections: Collection[] = await collectionsService.readByQuery();

Expand All @@ -38,17 +40,18 @@ export default defineHook(({ action }, extCtx) => {
let useIntersectionTypes = false;
generateTsTypes(collectionsData, useIntersectionTypes).then((types) => {
targetFiles.forEach((targetFile: string) => {
writeToFile('./', targetFile, types)
writeToFile('./', targetFile, disclaimerHeader + types)
logger.info(`Types synced into ${targetFile}`)
})
});
}

const onChange: ActionHandler = async ({ }, { schema }) => {
if (schema === null) {
throw new Error('schema is null');
}
listCollections(schema);
// Update the types when we start the server
saveTypescriptTypesToFile();


const onChange: ActionHandler = async () => {
saveTypescriptTypesToFile();
}

action('collections.create', onChange);
Expand All @@ -65,7 +68,7 @@ export default defineHook(({ action }, extCtx) => {
});


export function writeToFile(directoryPath: string, fileName: string, data: string) {
const writeToFile = (directoryPath: string, fileName: string, data: string) => {
try {
fs.mkdirSync(directoryPath, {recursive: true})
}
Expand All @@ -77,3 +80,9 @@ export function writeToFile(directoryPath: string, fileName: string, data: strin

fs.writeFileSync(`${directoryPath}/${fileName}`, data)
}

const disclaimerHeader = `/*
* This file is generated by 'directus-extensions-generate-types' script.
* Do not edit manually.
*/
`

0 comments on commit 545bc53

Please sign in to comment.