From f359a178aa7bf643ea7133ee2e510722db391c6f Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 19 Jun 2022 13:22:31 +0800 Subject: [PATCH] feat: support json5 for snippet --- package.json | 1 + pnpm-lock.yaml | 2 ++ src/global/json.global.ts | 8 +++++++- src/modules/snippet/snippet.model.ts | 1 + src/modules/snippet/snippet.service.ts | 13 +++++++++++++ 5 files changed, 24 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 3e31fda2..943359d6 100644 --- a/package.json +++ b/package.json @@ -107,6 +107,7 @@ "inquirer": "*", "isbot": "3.5.0", "js-yaml": "*", + "json5": "2.2.1", "jsonwebtoken": "8.5.1", "jszip": "3.10.0", "linkedom": "0.14.11", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d5f68947..7c5885bb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -82,6 +82,7 @@ specifiers: isbot: 3.5.0 jest: 28.1.1 js-yaml: '*' + json5: 2.2.1 jsonwebtoken: 8.5.1 jszip: 3.10.0 linkedom: 0.14.11 @@ -164,6 +165,7 @@ dependencies: inquirer: 8.2.4 isbot: 3.5.0 js-yaml: 4.1.0 + json5: 2.2.1 jsonwebtoken: 8.5.1 jszip: 3.10.0 linkedom: 0.14.11 diff --git a/src/global/json.global.ts b/src/global/json.global.ts index a0f55a1b..3cc79a2e 100644 --- a/src/global/json.global.ts +++ b/src/global/json.global.ts @@ -1,15 +1,21 @@ +import JSON5 from 'json5' + declare global { interface JSON { safeParse: typeof JSON.parse + + JSON5: typeof JSON5 } } export const registerJSONGlobal = () => { JSON.safeParse = (...rest) => { try { - return JSON.parse(...rest) + return JSON5.parse(...rest) } catch (error) { return null } } + + JSON.JSON5 = JSON5 } diff --git a/src/modules/snippet/snippet.model.ts b/src/modules/snippet/snippet.model.ts index fbaac5df..5a1683cf 100644 --- a/src/modules/snippet/snippet.model.ts +++ b/src/modules/snippet/snippet.model.ts @@ -15,6 +15,7 @@ import { BaseModel } from '~/shared/model/base.model' export enum SnippetType { JSON = 'json', + JSON5 = 'json5', Function = 'function', Text = 'text', YAML = 'yaml', diff --git a/src/modules/snippet/snippet.service.ts b/src/modules/snippet/snippet.service.ts index 520cab54..7eeea633 100644 --- a/src/modules/snippet/snippet.service.ts +++ b/src/modules/snippet/snippet.service.ts @@ -1,4 +1,5 @@ import { load } from 'js-yaml' +import JSON5 from 'json5' import { BadRequestException, @@ -77,6 +78,14 @@ export class SnippetService { } break } + case SnippetType.JSON5: { + try { + JSON5.parse(model.raw) + } catch { + throw new BadRequestException('content is not valid json5') + } + break + } case SnippetType.YAML: { try { load(model.raw) @@ -139,6 +148,10 @@ export class SnippetService { Reflect.set(model, 'data', JSON.parse(model.raw)) break } + case SnippetType.JSON5: { + Reflect.set(model, 'data', JSON5.parse(model.raw)) + break + } case SnippetType.YAML: { Reflect.set(model, 'data', load(model.raw)) break