-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtopic.ts
More file actions
47 lines (41 loc) · 1.6 KB
/
Copy pathtopic.ts
File metadata and controls
47 lines (41 loc) · 1.6 KB
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
// Resolve a topic_identifier against a headers or body object.
//
// Most identifiers are a plain key ("x-shopify-topic", "event"), but many
// providers nest the event type ("data.type", "events[].eventType"), so a
// flat lookup alone leaves those captures named "untitled-<hash>".
//
// Supported forms:
// event a plain key
// data.type a dotted path
// events[].eventType an array segment; the first element is used
// entry[].changes[].field nested array segments
//
// A literal key that exists is preferred over path interpretation, so a header
// whose real name contains a dot still resolves.
export const resolveTopic = (
source: any,
identifier: string
): string | undefined => {
if (source == null) return undefined;
if (typeof source === "object" && source[identifier] !== undefined) {
return scalarOrUndefined(source[identifier]);
}
let current = source;
for (const segment of identifier.split(".")) {
if (current == null) return undefined;
const is_array = segment.endsWith("[]");
current = current[is_array ? segment.slice(0, -2) : segment];
if (is_array) {
if (!Array.isArray(current)) return undefined;
current = current[0];
}
}
return scalarOrUndefined(current);
};
// Only a scalar can name a file. Anything else means the path landed somewhere
// unintended, and falling back to "untitled-" is more honest than
// "[object Object]".
export const scalarOrUndefined = (value: any): string | undefined =>
typeof value === "string" || typeof value === "number"
? String(value)
: undefined;