-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitize.ts
59 lines (52 loc) · 1.36 KB
/
sanitize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { createTemplateAction } from '@backstage/plugin-scaffolder-node';
import yaml from 'js-yaml';
// Add type annotations to fix TS2742
type SanitizeResourceInput = {
document: string;
};
type SanitizeResourceOutput = {
sanitized: string;
};
export const createSanitizeResource = () => {
return createTemplateAction<SanitizeResourceInput, SanitizeResourceOutput>({
id: 'cnoe:utils:sanitize',
schema: {
input: {
type: 'object',
required: ['document'],
properties: {
document: {
type: 'string',
title: 'Document',
description: 'The document to be sanitized',
},
},
},
},
async handler(ctx) {
const obj = yaml.load(ctx.input.document);
ctx.output('sanitized', yaml.dump(removeEmptyObjects(obj)));
},
});
};
// Remove empty elements from an object
function removeEmptyObjects(obj: any): any {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const newObj: any = Array.isArray(obj) ? [] : {};
for (const key in obj) {
const value = obj[key];
const newValue = removeEmptyObjects(value);
if (
!(
newValue === null ||
newValue === undefined ||
(typeof newValue === 'object' && Object.keys(newValue).length === 0)
)
) {
newObj[key] = newValue;
}
}
return newObj;
}