Skip to content

Instantly share code, notes, and snippets.

@spawnrider
Created March 15, 2022 07:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spawnrider/bdffb17660c91f8b42235b2ad18978cf to your computer and use it in GitHub Desktop.
Save spawnrider/bdffb17660c91f8b42235b2ad18978cf to your computer and use it in GitHub Desktop.
Custom endpoints for Directus snapshot import/export
import { defineEndpoint } from '@directus/extensions-sdk';
import * as fs from 'fs';
import * as path from 'path';
import { spawn } from 'child_process';
import busboy from 'busboy';
export default defineEndpoint((router) => {
router.get('/', (_req, res) => res.send('Custom endpoints for Directus snapshot import/export'));
router.get('/export', (_req, res) => {
if (!_req.accountability.admin) {
res.sendStatus(401);
return;
}
try {
const cmd = spawn('npx', ['directus', 'schema', 'snapshot', '--yes', './snapshot.yaml']);
cmd.stdout.on('data', (data : any) => {
console.log(`stdout: ${data}`);
});
cmd.stderr.on('data', (data : any) => {
console.error(`stderr: ${data}`);
});
cmd.on('close', (code : number) => {
console.log(`child process exited with code ${code}`);
if(code === 0) {
res.sendFile(path.join(__dirname + '/../../../snapshot.yaml'));
} else {
res.status(500).send('Issue while generating snapshot');
}
});
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});
router.post('/import', (_req, res) => {
if (!_req.accountability.admin) {
res.sendStatus(401);
return;
}
try {
const bb = busboy({ headers: _req.headers });
bb.on('file', (name, file, info) => {
file.pipe(fs.createWriteStream('./import.yaml'));
});
bb.on('close', () => {
const cmd = spawn('npx', ['directus', 'schema', 'apply', '--yes', './import.yaml']);
cmd.stdout.on('data', (data : any) => {
console.log(`stdout: ${data}`);
});
cmd.stderr.on('data', (data : any) => {
console.error(`stderr: ${data}`);
});
cmd.on('close', (code : number) => {
console.log(`child process exited with code ${code}`);
if(code === 0) {
res.json({'message': 'Schema successfully imported'});
} else {
res.status(500).send('Issue while importing snapshot');
}
});
});
_req.pipe(bb);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment