@@ -4,8 +4,12 @@ import mongoose from 'mongoose'
44import type { CollectionDefinition , DevtoolsServerContext , Resource , ServerFunctions } from '../types'
55import { capitalize , generateApiRoute , generateSchemaFile , pluralize , singularize } from '../utils'
66
7+ function safeExists ( path : unknown ) : path is string {
8+ return typeof path === 'string' && path . length > 0 && fs . existsSync ( path )
9+ }
10+
711export function setupResourceRPC ( { nuxt } : DevtoolsServerContext ) : any {
8- const config = nuxt . options . runtimeConfig . mongoose
12+ const config = nuxt . options . runtimeConfig . mongoose as any
913
1014 return {
1115 async generateResource ( collection : CollectionDefinition , resources : Resource [ ] ) {
@@ -15,7 +19,7 @@ export function setupResourceRPC({ nuxt }: DevtoolsServerContext): any {
1519
1620 if ( collection . fields ) {
1721 const schemaPath = join ( config . modelsDir , `${ singular } .schema.ts` )
18- if ( ! fs . existsSync ( schemaPath ) ) {
22+ if ( ! safeExists ( schemaPath ) ) {
1923 fs . ensureDirSync ( config . modelsDir )
2024 fs . writeFileSync ( schemaPath , generateSchemaFile ( dbName , collection . fields ) )
2125 }
@@ -36,7 +40,7 @@ export function setupResourceRPC({ nuxt }: DevtoolsServerContext): any {
3640 : routeTypes [ route . type ]
3741
3842 const filePath = join ( nuxt . options . serverDir , 'api' , plural , fileName )
39- if ( ! fs . existsSync ( filePath ) ) {
43+ if ( ! safeExists ( filePath ) ) {
4044 fs . ensureDirSync ( join ( nuxt . options . serverDir , `api/${ plural } ` ) )
4145 const content = generateApiRoute ( route . type , { model, by : route . by } )
4246 fs . writeFileSync ( filePath , content )
@@ -52,7 +56,7 @@ export function setupResourceRPC({ nuxt }: DevtoolsServerContext): any {
5256 async resourceSchema ( collection : string ) {
5357 const singular = singularize ( collection ) . toLowerCase ( )
5458 const schemaPath = join ( config . modelsDir , `${ singular } .schema.ts` )
55- if ( fs . existsSync ( schemaPath ) ) {
59+ if ( safeExists ( schemaPath ) ) {
5660 const content = fs . readFileSync ( schemaPath , 'utf-8' ) . match ( / s c h e m a : \{ ( .| \n ) * \} / g)
5761 if ( content ) {
5862 const schemaString = content [ 0 ] . replace ( 'schema: ' , '' ) . slice ( 0 , - 3 )
0 commit comments