/
UrlHelper.ts
83 lines (76 loc) · 2.53 KB
/
UrlHelper.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
interface CommitReferencedObjectUrl {
origin: string
streamId: string
commitId: string
}
export default class UrlHelper {
static async getResourceUrls(url: string): Promise<string[]> {
const parsed = new URL(url)
const streamId = url.split('/streams/')[1].substring(0, 10)
const objsUrls = []
// supports commit based urls
if (url.includes('commits')) {
const commitId = url.split('/commits/')[1].substring(0, 10)
const objUrl = await this.getCommitReferencedObjectUrl({
origin: parsed.origin,
streamId,
commitId
})
objsUrls.push(objUrl)
}
// object based urls
if (url.includes('objects')) objsUrls.push(url)
// supports urls that include overlay queries
// e.g., https://speckle.xyz/streams/a632e7a784/objects/457c45feffa6f954572e5e86fb6d4f25?overlay=cf8dc76247,f5adc1d991b3dceb4b5ad6b50f919a0e
if (url.includes('overlay=')) {
const searchParams = new URLSearchParams(parsed.search)
const resIds = searchParams.get('overlay')?.split(',')
if (resIds !== undefined) {
for (const resId of resIds) {
if (resId.length === 10) {
objsUrls.push(
await this.getCommitReferencedObjectUrl({
origin: parsed.origin,
streamId,
commitId: resId
} as CommitReferencedObjectUrl)
)
} else {
objsUrls.push(`${parsed.origin}/streams/${streamId}/objects/${resId}`)
}
}
}
}
return objsUrls
}
private static async getCommitReferencedObjectUrl(ref: CommitReferencedObjectUrl) {
const headers: { 'Content-Type': string; Authorization: string } = {
'Content-Type': 'application/json',
Authorization: ''
}
const authToken = localStorage.getItem(
ref.origin.includes('latest') ? 'AuthTokenLatest' : 'AuthToken'
)
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`
}
const res = await fetch(`${ref.origin}/graphql`, {
method: 'POST',
headers,
body: JSON.stringify({
query: `
query Stream($streamId: String!, $commitId: String!) {
stream(id: $streamId) {
commit(id: $commitId) {
referencedObject
}
}
}
`,
variables: { streamId: ref.streamId, commitId: ref.commitId }
})
})
const { data } = await res.json()
return `${ref.origin}/streams/${ref.streamId}/objects/${data.stream.commit.referencedObject}`
}
}