chore: refactor

This commit is contained in:
arashsheyda
2023-04-25 16:27:06 +03:00
parent cfc255c33b
commit a2cf4656eb

View File

@ -7,45 +7,39 @@ import { capitalize, pluralize, singularize } from '../utils/formatting'
export function setupResourceRPC({ nuxt }: NuxtDevtoolsServerContext): any {
return {
// TODO: maybe separate functions
async generateResource(collection: Collection, resources: Resource[]) {
const singular = singularize(collection.name).toLowerCase()
const plural = pluralize(collection.name).toLowerCase()
const dbName = capitalize(singular)
if (collection.fields) {
if (!fs.existsSync(resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`))) {
const schemaPath = resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`)
if (!fs.existsSync(schemaPath)) {
fs.ensureDirSync(resolve(nuxt.options.serverDir, 'utils/models'))
fs.writeFileSync(
resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`),
generateSchemaFile(dbName, collection.fields),
)
fs.writeFileSync(schemaPath, generateSchemaFile(dbName, collection.fields))
}
const model = { name: dbName, path: `${singular}.schema` }
fs.ensureDirSync(resolve(nuxt.options.serverDir, `api/${plural}`))
// create resources
// TODO: fix this
resources.forEach((route: any) => {
let fileName = ''
if (route.type === 'index')
fileName = 'index.get.ts'
const routeTypes = {
index: 'index.get.ts',
create: 'create.post.ts',
show: (by: string) => `${by}.get.ts`,
put: (by: string) => `${by}.put.ts`,
delete: (by: string) => `${by}.delete.ts`,
}
resources.forEach((route: Resource) => {
const fileName = typeof routeTypes[route.type] === 'function'
? (routeTypes[route.type] as any)(route.by)
: routeTypes[route.type]
if (route.type === 'create')
fileName = 'create.post.ts'
if (route.type === 'show')
fileName = `[_${route.by}].get.ts`.replace('_', '')
if (route.type === 'put')
fileName = `[_${route.by}].put.ts`.replace('_', '')
if (route.type === 'delete')
fileName = `[_${route.by}].delete.ts`.replace('_', '')
if (!fs.existsSync(resolve(nuxt.options.serverDir, `api/${plural}`, fileName))) {
const filePath = resolve(nuxt.options.serverDir, 'api', plural, fileName)
if (!fs.existsSync(filePath)) {
fs.ensureDirSync(resolve(nuxt.options.serverDir, `api/${plural}`))
const content = generateApiRoute(route.type, { model, by: route.by })
fs.writeFileSync(resolve(nuxt.options.serverDir, 'api', plural, fileName), content)
fs.writeFileSync(filePath, content)
}
})
}
@ -53,8 +47,6 @@ export function setupResourceRPC({ nuxt }: NuxtDevtoolsServerContext): any {
// create collection if not exists
if (!mongoose.connection.modelNames().includes(dbName))
await mongoose.connection.db.createCollection(plural)
// create rows and columns
},
async resourceSchema(collection: string) {
// TODO: use magicast