Created
September 11, 2023 08:07
-
-
Save h-sigma/3856cda854f73231fa2a107bf51e4362 to your computer and use it in GitHub Desktop.
Basic File Transform as Node Script
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
#!/usr/bin/env node | |
'use strict'; | |
const fs = require('fs'); | |
const filePath = process.argv[2]; | |
if (!filePath) { | |
console.error('Please provide the path to the file to transform.'); | |
process.exit(1); | |
} | |
if (!fs.existsSync(filePath)) { | |
console.error('File at given path does not exist.'); | |
process.exit(1); | |
} | |
console.log('Transforming file at path: ' + filePath); | |
const fileContents = fs.readFileSync(filePath, 'utf8'); | |
// Find schema names in file | |
const patternStart = 'export const schemas = {'; | |
const idxStart = fileContents.indexOf(patternStart); | |
if (idxStart === -1) { | |
console.error('Could not find start of schema definitions in file.'); | |
process.exit(1); | |
} | |
const idxEnd = fileContents.indexOf('};', idxStart); | |
const schemaNames = fileContents | |
.substring(idxStart + patternStart.length, idxEnd) | |
.replace(/\s/g, '') | |
.split(',') | |
.filter(schemaName => schemaName.length > 0); | |
// From schema names, generate the lines to append to the file | |
const lines = schemaNames.flatMap(schemaName => { | |
return [ | |
`export { ${schemaName} };`, | |
`export type ${schemaName} = z.output<typeof schemas.${schemaName}>;`, | |
'' | |
] | |
}); | |
const outputContents = fileContents + '\n\n // Individual exports of schemas: \n' + lines.join('\n'); | |
fs.writeFileSync('./output.ts', outputContents, 'utf8'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment