From d15259715523f29f27433a835491d56d5ae96f3c Mon Sep 17 00:00:00 2001 From: arashsheyda Date: Mon, 24 Apr 2023 22:15:44 +0300 Subject: [PATCH] fix: auto-import models --- src/server-rpc/resource.ts | 15 ++++++--------- src/utils/schematics.ts | 3 +-- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/server-rpc/resource.ts b/src/server-rpc/resource.ts index defdf8c..fafdded 100644 --- a/src/server-rpc/resource.ts +++ b/src/server-rpc/resource.ts @@ -13,10 +13,10 @@ export function setupResourceRPC({ nuxt }: NuxtDevtoolsServerContext): any { const dbName = capitalize(singular) if (collection.fields) { - if (!fs.existsSync(resolve(nuxt.options.serverDir, 'models', `${singular}.schema.ts`))) { - fs.ensureDirSync(resolve(nuxt.options.serverDir, 'models')) + if (!fs.existsSync(resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`))) { + fs.ensureDirSync(resolve(nuxt.options.serverDir, 'utils/models')) fs.writeFileSync( - resolve(nuxt.options.serverDir, 'models', `${singular}.schema.ts`), + resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`), generateSchemaFile(dbName, collection.fields), ) } @@ -57,14 +57,11 @@ export function setupResourceRPC({ nuxt }: NuxtDevtoolsServerContext): any { // create rows and columns }, async resourceSchema(collection: string) { - // get schema file if exists + // TODO: use magicast const singular = singularize(collection).toLowerCase() - - if (fs.existsSync(resolve(nuxt.options.serverDir, 'models', `${singular}.schema.ts`))) { - const schemaPath = resolve(nuxt.options.serverDir, 'models', `${singular}.schema.ts`) - + const schemaPath = resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`) + if (fs.existsSync(schemaPath)) { const content = fs.readFileSync(schemaPath, 'utf-8').match(/schema: \{(.|\n)*\}/g) - if (content) { const schemaString = content[0].replace('schema: ', '').slice(0, -3) // eslint-disable-next-line no-eval diff --git a/src/utils/schematics.ts b/src/utils/schematics.ts index b70e25b..ad1ac49 100644 --- a/src/utils/schematics.ts +++ b/src/utils/schematics.ts @@ -26,7 +26,6 @@ export const ${name}Schema = defineMongooseModel({ export function generateApiRoute(action: string, { model, by }: { model: { name: string; path: string }; by?: string }) { const modelName = capitalize(model.name) - const schemaImport = `import { ${modelName}Schema } from '../../models/${model.path}'\n\n` const operation = { index: `return await ${modelName}Schema.find({})`, create: `return await new ${modelName}Schema(body).save()`, @@ -42,7 +41,7 @@ export function generateApiRoute(action: string, { model, by }: { model: { name: return error }` - return `${schemaImport}export default defineEventHandler(async (event) => { + return `export default defineEventHandler(async (event) => { ${(action === 'create' || action === 'put') ? `const body = await readBody(event)\n ${main}` : main} }) `