@@ -10,6 +10,14 @@ const isEgern = 'object' == typeof egern;
10
10
const isLanceX = 'undefined' != typeof $native ;
11
11
const isGUIforCores = typeof $Plugins !== 'undefined' ;
12
12
13
+ function isPlainObject ( obj ) {
14
+ return (
15
+ obj !== null &&
16
+ typeof obj === 'object' &&
17
+ [ null , Object . prototype ] . includes ( Object . getPrototypeOf ( obj ) )
18
+ ) ;
19
+ }
20
+
13
21
export class OpenAPI {
14
22
constructor ( name = 'untitled' , debug = false ) {
15
23
this . name = name ;
@@ -62,29 +70,50 @@ export class OpenAPI {
62
70
const basePath =
63
71
eval ( 'process.env.SUB_STORE_DATA_BASE_PATH' ) || '.' ;
64
72
let rootPath = `${ basePath } /root.json` ;
73
+ const backupRootPath = `${ basePath } /root_${ Date . now ( ) } .json` ;
65
74
66
75
this . log ( `Root path: ${ rootPath } ` ) ;
67
- if ( ! this . node . fs . existsSync ( rootPath ) ) {
76
+ if ( this . node . fs . existsSync ( rootPath ) ) {
77
+ try {
78
+ this . root = JSON . parse (
79
+ this . node . fs . readFileSync ( `${ rootPath } ` ) ,
80
+ ) ;
81
+ } catch ( e ) {
82
+ this . node . fs . copyFileSync ( rootPath , backupRootPath ) ;
83
+ this . error (
84
+ `Failed to parse ${ rootPath } : ${ e . message } . Backup created at ${ backupRootPath } ` ,
85
+ ) ;
86
+ }
87
+ }
88
+ if ( ! isPlainObject ( this . root ) ) {
68
89
this . node . fs . writeFileSync ( rootPath , JSON . stringify ( { } ) , {
69
- flag : 'wx ' ,
90
+ flag : 'w ' ,
70
91
} ) ;
71
92
this . root = { } ;
72
- } else {
73
- this . root = JSON . parse (
74
- this . node . fs . readFileSync ( `${ rootPath } ` ) ,
75
- ) ;
76
93
}
77
94
78
95
// create a json file with the given name if not exists
79
96
let fpath = `${ basePath } /${ this . name } .json` ;
97
+ const backupPath = `${ basePath } /${ this . name } _${ Date . now ( ) } .json` ;
98
+
80
99
this . log ( `Data path: ${ fpath } ` ) ;
81
- if ( ! this . node . fs . existsSync ( fpath ) ) {
100
+ if ( this . node . fs . existsSync ( fpath ) ) {
101
+ try {
102
+ this . cache = JSON . parse (
103
+ this . node . fs . readFileSync ( `${ fpath } ` ) ,
104
+ ) ;
105
+ } catch ( e ) {
106
+ this . node . fs . copyFileSync ( fpath , backupPath ) ;
107
+ this . error (
108
+ `Failed to parse ${ fpath } : ${ e . message } . Backup created at ${ backupPath } ` ,
109
+ ) ;
110
+ }
111
+ }
112
+ if ( ! isPlainObject ( this . cache ) ) {
82
113
this . node . fs . writeFileSync ( fpath , JSON . stringify ( { } ) , {
83
- flag : 'wx ' ,
114
+ flag : 'w ' ,
84
115
} ) ;
85
116
this . cache = { } ;
86
- } else {
87
- this . cache = JSON . parse ( this . node . fs . readFileSync ( `${ fpath } ` ) ) ;
88
117
}
89
118
}
90
119
}
0 commit comments