Skip to content

Instantly share code, notes, and snippets.

@zhyupe
Created October 14, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhyupe/632ae38f040bd40b846fd37f607bfc95 to your computer and use it in GitHub Desktop.
Save zhyupe/632ae38f040bd40b846fd37f607bfc95 to your computer and use it in GitHub Desktop.
TypeORM ormconfig.json loader
const glob = require('glob');
const jsValidJson = (value) => JSON.stringify(value)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
module.exports = function(source) {
const obj = typeof source === 'string' ? JSON.parse(source) : source;
// loadFileClasses is copied from TypeORM, MIT License, Copyright (c) 2015-2016 Yakdu. http://typeorm.github.io
// https://github.com/typeorm/typeorm/blob/master/src/util/DirectoryExportedClassesLoader.ts#L9
return `
var typeorm = require('typeorm');
function loadFileClasses(exported, allLoaded) {
if (typeof exported === "function" || exported instanceof typeorm.EntitySchema) {
allLoaded.push(exported);
}
else if (Array.isArray(exported)) {
exported.forEach(function (i) { return loadFileClasses(i, allLoaded); });
}
else if (typeof exported === "object") {
Object.keys(exported).forEach(function (key) { return loadFileClasses(exported[key], allLoaded); });
}
return allLoaded;
}
module.exports = { ${ Object.keys(obj).map(key => {
let value = obj[key];
let stringified = false;
if (key === 'entities') {
let array = [];
value.forEach(pattern => glob.sync(pattern).forEach(entity => {
this.addDependency(entity);
array.push(`require(${jsValidJson(entity)})`);
}))
value = `loadFileClasses([${array.join(', ')}], [])`;
stringified = true;
}
if (!stringified) {
value = jsValidJson(value);
}
return `${jsValidJson(key)}: ${value}`
}).join(', ') } };`;
}
module.exports = {
module: {
rules: [{
test: /ormconfig\.json/,
type: 'javascript/auto',
loader: path.resolve('ormconfig-loader.js')
}]
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment