/
uniquenessTags.ts
49 lines (42 loc) · 1.17 KB
/
uniquenessTags.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
import { createRulesetFunction } from '@stoplight/spectral-core';
import type { IFunctionResult } from '@stoplight/spectral-core';
type Tags = Array<{ name: string }>;
function getDuplicateTagsIndexes(tags: Tags): number[] {
return tags
.map(item => item.name)
.reduce<number[]>((acc, item, i, arr) => {
if (arr.indexOf(item) !== i) {
acc.push(i);
}
return acc;
}, []);
}
export default createRulesetFunction<Tags, null>(
{
input: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string',
},
},
},
},
options: null,
},
function uniquenessTags(targetVal, _, ctx) {
const duplicatedTags = getDuplicateTagsIndexes(targetVal);
if (duplicatedTags.length === 0) return [];
const results: IFunctionResult[] = [];
for (const duplicatedIndex of duplicatedTags) {
const duplicatedTag = targetVal[duplicatedIndex].name;
results.push({
message: `"tags" object contains duplicate tag name "${duplicatedTag}".`,
path: [...ctx.path, duplicatedIndex, 'name'],
});
}
return results;
},
);