Created
July 30, 2022 22:14
-
-
Save zadokdaniel/ea4dd31e13957c717ffb26e238f25173 to your computer and use it in GitHub Desktop.
knex-types interfaces into objects for easily use with joins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getInterfacesNamesAndProperties(interfacesSourceCodeTXT) { | |
const interfaceRegex = | |
/export\s*type\s*(?<interfaceName>\w+)\s*=\s{(\s*?.*?)*?};/g; | |
const keyRegex = /(?<key>\w+):\s*[\w |]*;/g; | |
let results = {}; | |
for (const interface of txt.matchAll(interfaceRegex)) { | |
results[interface.groups.interfaceName] = Array.from( | |
interface[0].matchAll(keyRegex) | |
).map((result) => result.groups.key); | |
} | |
return results; | |
} | |
const camelToSnakeCase = (str) => | |
`${str[0].toLowerCase()}${str.slice(1)}`.replace( | |
/[A-Z]/g, | |
(letter) => `_${letter.toLowerCase()}` | |
); | |
function getAsObject(name, properties) { | |
const sc_name = camelToSnakeCase(name); | |
return ` | |
export const ${name} = { | |
${properties | |
.map( | |
(property) => | |
`${property}: "${sc_name}.${camelToSnakeCase(property)}"` | |
) | |
.join(",")} | |
toString() { | |
return "${sc_name}" | |
} | |
}; | |
`; | |
} | |
function generateObjectsFromInterfaces() { | |
const data = getInterfacesNamesAndProperties(txt); | |
let result = ""; | |
for (const key in data) { | |
result += getAsObject(key, data[key]); | |
} | |
return result; | |
} |
results
export type PaymentMethods = {
id: number;
name: string | null;
created_at: Date | null;
updated_at: Date | null;
display_name: string | null;
deleted_at: Date | null;
};
BECOMES
export const PaymentMethods = {
id: "payment_methods.id",
name: "payment_methods.name",
created_at: "payment_methods.created_at",
updated_at: "payment_methods.updated_at",
display_name: "payment_methods.display_name",
deleted_at: "payment_methods.deleted_at",
toString() {
return "payment_methods";
},
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BECOMES