Skip to content

Commit fcd803e

Browse files
authored
Merge pull request #608 from Code-Hex/fix/602
fixed #602
2 parents 6625c0e + c8eb9cf commit fcd803e

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

src/directive.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,10 +182,15 @@ function stringify(arg: any, quoteString?: boolean): string {
182182
if (isConvertableRegexp(arg))
183183
return arg;
184184

185+
const v = tryEval(arg)
186+
if (v !== undefined)
187+
arg = v
188+
185189
if (quoteString)
186190
return JSON.stringify(arg);
187191
}
188-
if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint')
192+
193+
if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint' || arg === 'undefined' || arg === null)
189194
return `${arg}`;
190195

191196
return JSON.stringify(arg);
@@ -199,6 +204,16 @@ function apiArgsFromConstValueNode(value: ConstValueNode): any[] {
199204
return [val];
200205
}
201206

207+
function tryEval(maybeValidJavaScript: string): any | undefined {
208+
try {
209+
// eslint-disable-next-line no-eval
210+
return eval(maybeValidJavaScript)
211+
}
212+
catch {
213+
return undefined
214+
}
215+
}
216+
202217
export const exportedForTesting = {
203218
applyArgToApiSchemaTemplate,
204219
buildApiFromDirectiveObjectArguments,

tests/directive.spec.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,38 @@ describe('format directive config', () => {
190190
},
191191
want: 'true',
192192
},
193+
{
194+
name: 'eval number',
195+
args: {
196+
template: '$1',
197+
apiArgs: ['10 + 1'],
198+
},
199+
want: '11',
200+
},
201+
{
202+
name: 'eval boolean',
203+
args: {
204+
template: '$1',
205+
apiArgs: ['!true'],
206+
},
207+
want: 'false',
208+
},
209+
{
210+
name: 'eval template with number',
211+
args: {
212+
template: '$1 + 1',
213+
apiArgs: [10],
214+
},
215+
want: '11',
216+
},
217+
{
218+
name: 'eval template with boolean',
219+
args: {
220+
template: '$1 && false',
221+
apiArgs: [true],
222+
},
223+
want: 'false',
224+
},
193225
{
194226
name: 'array',
195227
args: {
@@ -206,6 +238,22 @@ describe('format directive config', () => {
206238
},
207239
want: `{"hello":"world"}`,
208240
},
241+
{
242+
name: 'undefined',
243+
args: {
244+
template: '$1',
245+
apiArgs: ['undefined'],
246+
},
247+
want: 'undefined',
248+
},
249+
{
250+
name: 'null',
251+
args: {
252+
template: '$1',
253+
apiArgs: ['null'],
254+
},
255+
want: 'null',
256+
},
209257
{
210258
name: 'multiple',
211259
args: {

0 commit comments

Comments
 (0)