Skip to content

Commit

Permalink
Merge pull request #75 from easyops-cn/nlicro/yaml_stringify_sort_keys
Browse files Browse the repository at this point in the history
feat: yamlStringify support sortKeys
  • Loading branch information
weareoutman authored Nov 20, 2023
2 parents 44e93de + 5dda926 commit 4d32504
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 9 deletions.
4 changes: 3 additions & 1 deletion etc/brick-next-pipes.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;

```
20 changes: 13 additions & 7 deletions src/pipes/yamlStringify.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ describe("yamlStringify", () => {
const circularValue: Record<string, unknown> = {};
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);
}
);
});
8 changes: 7 additions & 1 deletion src/pipes/yamlStringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand All @@ -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
Expand Down

0 comments on commit 4d32504

Please sign in to comment.