From 5dda9265224e1ee607b3bcbfb6cc581a5d7e1c4b Mon Sep 17 00:00:00 2001 From: nlicroshan Date: Mon, 20 Nov 2023 17:09:03 +0800 Subject: [PATCH] feat: yamlStringify support sortKeys --- etc/brick-next-pipes.api.md | 4 +++- src/pipes/yamlStringify.spec.ts | 20 +++++++++++++------- src/pipes/yamlStringify.ts | 8 +++++++- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/etc/brick-next-pipes.api.md b/etc/brick-next-pipes.api.md index 9301245..fafc90a 100644 --- a/etc/brick-next-pipes.api.md +++ b/etc/brick-next-pipes.api.md @@ -184,6 +184,8 @@ export function unitFormat(value: number, unit: string, precision?: number, targ export function yaml(value: string): unknown; // @public -export function yamlStringify(value: unknown, indent?: number): string; +export function yamlStringify(value: unknown, indent?: number, opts?: { + sortKeys?: boolean; +}): string; ``` diff --git a/src/pipes/yamlStringify.spec.ts b/src/pipes/yamlStringify.spec.ts index cbddf13..a5bcbfa 100644 --- a/src/pipes/yamlStringify.spec.ts +++ b/src/pipes/yamlStringify.spec.ts @@ -6,17 +6,23 @@ describe("yamlStringify", () => { const circularValue: Record = {}; circularValue.self = circularValue; - const testCases: [unknown, number, string][] = [ - ["3", undefined, "'3'\n"], - [{ name: "foo" }, undefined, "name: foo\n"], - [/re/, undefined, ""], - [circularValue, undefined, undefined], + const testCases: [unknown, number, { sortKeys?: boolean }, string][] = [ + ["3", undefined, undefined, "'3'\n"], + [{ name: "foo", age: 18 }, undefined, undefined, "name: foo\nage: 18\n"], + [ + { name: "foo", age: 18 }, + undefined, + { sortKeys: true }, + "age: 18\nname: foo\n", + ], + [/re/, undefined, undefined, ""], + [circularValue, undefined, undefined, undefined], ]; test.each(testCases)( "yamlStringify(%j, %j) should return %j", - (value, indent, output) => { - expect(yamlStringify(value, indent)).toEqual(output); + (value, indent, opts, output) => { + expect(yamlStringify(value, indent, opts)).toEqual(output); } ); }); diff --git a/src/pipes/yamlStringify.ts b/src/pipes/yamlStringify.ts index 1b4635e..1652ce4 100644 --- a/src/pipes/yamlStringify.ts +++ b/src/pipes/yamlStringify.ts @@ -9,10 +9,15 @@ import { safeDump, JSON_SCHEMA } from "js-yaml"; * * @param value - 输入值。 * @param indent - 空格缩进数量(默认为 `2`)。 + * @param opts - 选项 * * @returns 序列化后的字符串;如果序列化失败(例如包含循环引用)返回 `undefined`。 */ -export function yamlStringify(value: unknown, indent = 2): string { +export function yamlStringify( + value: unknown, + indent = 2, + opts?: { sortKeys?: boolean } +): string { let result; try { result = safeDump(value, { @@ -21,6 +26,7 @@ export function yamlStringify(value: unknown, indent = 2): string { skipInvalid: true, noRefs: true, noCompatMode: true, + sortKeys: opts?.sortKeys, }); } catch (e) { // eslint-disable-next-line no-console