@@ -11,7 +11,8 @@ import {
1111 map ,
1212 uniq ,
1313} from 'lodash' ;
14- import { readFileSync } from 'node:fs' ;
14+ import { existsSync , readFileSync } from 'node:fs' ;
15+ import { writeFile } from 'node:fs/promises' ;
1516import type { OpenAPI , OpenAPIV2 , OpenAPIV3 } from 'openapi-types' ;
1617import converter from 'swagger2openapi' ;
1718
@@ -258,11 +259,44 @@ function isJSONString(str: string) {
258259 }
259260}
260261
262+ function readFileSafelySync ( filePath : string ) {
263+ if ( ! existsSync ( filePath ) ) {
264+ logError ( `文件 ${ filePath } 不存在` ) ;
265+ return null ;
266+ }
267+
268+ try {
269+ return readFileSync ( filePath , 'utf-8' ) ;
270+ } catch ( error ) {
271+ logError ( `读取文件 ${ filePath } 时出错:` , error ) ;
272+ return null ;
273+ }
274+ }
275+
276+ async function writeFileAsync ( filePath : string , content : string ) {
277+ try {
278+ await writeFile ( filePath , content , 'utf8' ) ;
279+ } catch ( error ) {
280+ logError ( `文件 ${ filePath } 写入失败` ) ;
281+ }
282+ }
283+
261284export async function translateChineseModuleNodeToEnglish (
262285 openAPI : OpenAPIObject
263286) {
287+ const content = readFileSafelySync (
288+ process . cwd ( ) + '/openapi-ts-request.cache.json'
289+ ) ;
290+ let i18n : Record < string , string > | null = { } ;
291+
292+ if ( content !== null ) {
293+ if ( isJSONString ( content ) ) {
294+ i18n = JSON . parse ( content ) as Record < string , string > ;
295+ }
296+ }
297+
264298 return new Promise < Record < string , string > | boolean > ( ( resolve , reject ) => {
265- const translateMap : Record < string , string > = { } ;
299+ const translateMap : Record < string , string > = i18n ;
266300 const operations = [ ] as OperationObject [ ] ;
267301 let tags : string [ ] = [ ] ;
268302
@@ -281,7 +315,7 @@ export async function translateChineseModuleNodeToEnglish(
281315 void Promise . all (
282316 map ( uniq ( tags ) , ( tagName ) => {
283317 return new Promise ( ( resolve ) => {
284- if ( tagName && / [ \u3220 - \uFA29 ] / . test ( tagName ) ) {
318+ if ( tagName && / [ \u3220 - \uFA29 ] / . test ( tagName ) && ! i18n [ tagName ] ) {
285319 void translate ( tagName , null , 'en' )
286320 . then ( ( translateRes ) => {
287321 const text = camelCase ( translateRes ?. translation ) ;
@@ -309,6 +343,10 @@ export async function translateChineseModuleNodeToEnglish(
309343 } ) ;
310344 } ) ;
311345 resolve ( translateMap ) ;
346+ void writeFileAsync (
347+ process . cwd ( ) + '/openapi-ts-request.cache.json' ,
348+ JSON . stringify ( translateMap , null , 2 )
349+ ) ;
312350 } )
313351 . catch ( ( ) => {
314352 reject ( false ) ;
0 commit comments