|
| 1 | +import { defineHook } from '@directus/extensions-sdk'; |
| 2 | +import { readFile } from 'node:fs/promises'; |
| 3 | +import { load as loadYaml } from 'js-yaml'; |
| 4 | +import { glob as globCB } from 'glob'; |
| 5 | +import { promisify } from "util"; |
| 6 | +export default defineHook(async ({ init }, { services, getSchema, database, env, logger }) => { |
| 7 | + const SEED_FILES = env.SEED_FILES; |
| 8 | + const glob = promisify(globCB); |
| 9 | + const accountability = { |
| 10 | + admin: true |
| 11 | + }; |
| 12 | + init('app.before', async () => { |
| 13 | + if (!SEED_FILES) { |
| 14 | + logger.info('SEED_FILES is not set, skipping seeding'); |
| 15 | + return; |
| 16 | + } |
| 17 | + const sourceFiles = (await Promise.all(SEED_FILES |
| 18 | + .split(':') |
| 19 | + .map((pattern) => glob(pattern)))) |
| 20 | + .flatMap(set => set) |
| 21 | + .sort(); |
| 22 | + if (sourceFiles.length === 0) { |
| 23 | + logger.warn('No seed files found'); |
| 24 | + return; |
| 25 | + } |
| 26 | + else { |
| 27 | + logger.info(`Found ${sourceFiles.length} seed files:`); |
| 28 | + sourceFiles.forEach((file) => { |
| 29 | + logger.info(` - ${file}`); |
| 30 | + }); |
| 31 | + } |
| 32 | + for (let sourceFile of sourceFiles) { |
| 33 | + const fileContents = await readFile(sourceFile, 'utf8'); |
| 34 | + const dataSource = loadYaml(fileContents); |
| 35 | + for (let collectionName in dataSource) { |
| 36 | + const collection = new services.ItemsService(collectionName, { |
| 37 | + knex: database, |
| 38 | + schema: await getSchema(), |
| 39 | + accountability, |
| 40 | + }); |
| 41 | + const results = await collection.upsertMany(dataSource[collectionName]); |
| 42 | + logger.info(`Upserted ${results.length} items into ${collectionName}`); |
| 43 | + } |
| 44 | + } |
| 45 | + }); |
| 46 | +}); |
0 commit comments