1
- /**
2
- * This file is responsible for generating Nest.js metadata for the API.
3
- * Metadata generation is required when using SWC with Nest.js due to SWC
4
- * not natively supporting Typescript, which is required to use the `reflect-metadata`
5
- * API and in turn, resolve types for the OpenAPI specification.
6
- *
7
- * @see https://docs.nestjs.com/recipes/swc#monorepo-and-cli-plugins
8
- */
9
1
import fs from 'node:fs' ;
10
2
import path from 'node:path' ;
3
+ import { fileURLToPath } from 'node:url' ;
11
4
import { PluginMetadataGenerator } from '@nestjs/cli/lib/compiler/plugins' ;
12
5
import { ReadonlyVisitor } from '@nestjs/swagger/dist/plugin' ;
13
6
14
- const tsconfigPath = 'tsconfig.build.json' ;
15
- const srcPath = path . join ( __dirname , '..' , 'src' ) ;
16
- const metadataPath = path . join ( srcPath , 'metadata.ts' ) ;
7
+ // Get the current file's directory
8
+ const __filename = fileURLToPath ( import . meta. url ) ;
9
+ const __dirname = path . dirname ( __filename ) ;
10
+
11
+ // More precise path resolution
12
+ const projectRoot = path . resolve ( __dirname , '..' , '..' ) ;
13
+ const apiRoot = path . resolve ( projectRoot , 'api' ) ;
14
+ const srcPath = path . resolve ( apiRoot , 'src' ) ;
15
+ const metadataPath = path . resolve ( srcPath , 'metadata.ts' ) ;
16
+
17
+ // Ensure directories exist
18
+ fs . mkdirSync ( path . dirname ( metadataPath ) , { recursive : true } ) ;
17
19
18
20
/*
19
21
* We create an empty metadata file to ensure that files importing `metadata.ts`
@@ -24,9 +26,15 @@ const defaultContent = `export default async () => { return {}; };`;
24
26
fs . writeFileSync ( metadataPath , defaultContent , 'utf8' ) ;
25
27
console . log ( 'metadata.ts file has been generated with default content.' ) ;
26
28
27
- const generator = new PluginMetadataGenerator ( ) ;
28
- generator . generate ( {
29
- visitors : [ new ReadonlyVisitor ( { introspectComments : true , pathToSource : srcPath } ) ] ,
30
- outputDir : srcPath ,
31
- tsconfigPath,
32
- } ) ;
29
+ // Wrap in try-catch for better error handling
30
+ try {
31
+ const generator = new PluginMetadataGenerator ( ) ;
32
+ generator . generate ( {
33
+ visitors : [ new ReadonlyVisitor ( { introspectComments : true , pathToSource : srcPath } ) ] ,
34
+ outputDir : srcPath ,
35
+ tsconfigPath : 'tsconfig.build.json' ,
36
+ } ) ;
37
+ } catch ( error ) {
38
+ console . error ( 'Error generating metadata:' , error ) ;
39
+ process . exit ( 1 ) ;
40
+ }
0 commit comments