You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.9 KiB
46 lines
1.9 KiB
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { resolve, dirname } from 'node:path'
|
|
|
|
const root = fileURLToPath(new URL('../', import.meta.url))
|
|
const [name] = process.argv.slice(2)
|
|
if (!name || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || name.length > 48 || name === 'then') {
|
|
console.error('Usage: pnpm module:new <lowercase-module-name>')
|
|
process.exitCode = 1
|
|
} else {
|
|
const namespace = name.replace(/-([a-z0-9])/g, (_match, char) => char.toUpperCase())
|
|
const factory = 'create' + namespace[0].toUpperCase() + namespace.slice(1) + 'Router'
|
|
const moduleFile = resolve(root, 'src/main/modules/' + name + '.ts')
|
|
const compositionFile = resolve(root, 'src/main/trpc/app-router.ts')
|
|
const composition = readFileSync(compositionFile, 'utf8')
|
|
if (
|
|
existsSync(moduleFile) ||
|
|
existsSync(resolve(root, 'src/main/modules/' + name)) ||
|
|
new RegExp('\\b' + namespace + ':').test(composition) ||
|
|
!composition.includes('return router({')
|
|
) {
|
|
throw new Error('Module exists or composition anchor changed; no files written')
|
|
}
|
|
const source =
|
|
"import { z } from 'zod'\nimport { router, procedure } from '../trpc/runtime'\n\nexport function " +
|
|
factory +
|
|
"() {\n return router({\n echo: procedure(['main']).input(z.string().max(1000)).output(z.string()).query(({ input }) => input)\n })\n}\n"
|
|
const nextComposition =
|
|
'import { ' +
|
|
factory +
|
|
" } from '../modules/" +
|
|
name +
|
|
"'\n" +
|
|
composition.replace(
|
|
'return router({',
|
|
'return router({\n ' + namespace + ': ' + factory + '(),'
|
|
)
|
|
mkdirSync(dirname(moduleFile), { recursive: true })
|
|
writeFileSync(moduleFile, source, { flag: 'wx' })
|
|
writeFileSync(compositionFile, nextComposition)
|
|
console.log(
|
|
'Created trpc.' +
|
|
namespace +
|
|
'.echo.query(message). Schema, permissions and resolver live in one module. Run pnpm format && pnpm check.'
|
|
)
|
|
}
|
|
|