-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAccessRepository.ts
More file actions
179 lines (147 loc) · 5.45 KB
/
AccessRepository.ts
File metadata and controls
179 lines (147 loc) · 5.45 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import { ApiConfig, DataverseApiAuthMechanism } from '../../../core/infra/repositories/ApiConfig'
import { WriteError } from '../../../core/domain/repositories/WriteError'
import { ApiConstants } from '../../../core/infra/repositories/ApiConstants'
import { ApiRepository } from '../../../core/infra/repositories/ApiRepository'
import {
buildRequestConfig,
buildRequestUrl
} from '../../../core/infra/repositories/apiConfigBuilders'
import { GuestbookResponseDTO } from '../../domain/dtos/GuestbookResponseDTO'
import { IAccessRepository } from '../../domain/repositories/IAccessRepository'
export class AccessRepository extends ApiRepository implements IAccessRepository {
private readonly accessResourceName = 'access'
public async submitGuestbookForDatafileDownload(
fileId: number | string,
guestbookResponse: GuestbookResponseDTO,
format?: string
): Promise<string> {
const endpoint = this.buildApiEndpoint(`${this.accessResourceName}/datafile`, undefined, fileId)
const queryParams = format ? { signed: true, format } : { signed: true }
return await this.submitGuestbookDownload(endpoint, guestbookResponse, queryParams)
}
public async submitGuestbookForDatafilesDownload(
fileIds: Array<number>,
guestbookResponse: GuestbookResponseDTO,
format?: string
): Promise<string> {
const queryParams = format ? { signed: true, format } : { signed: true }
return await this.submitGuestbookDownload(
this.buildApiEndpoint(
this.accessResourceName,
`datafiles/${Array.isArray(fileIds) ? fileIds.join(',') : fileIds}`
),
guestbookResponse,
queryParams
)
}
public async submitGuestbookForDatasetDownload(
datasetId: number | string,
guestbookResponse: GuestbookResponseDTO,
format?: string
): Promise<string> {
const endpoint = this.buildApiEndpoint(
`${this.accessResourceName}/dataset`,
undefined,
datasetId
)
const queryParams = format ? { signed: true, format } : { signed: true }
return await this.submitGuestbookDownload(endpoint, guestbookResponse, queryParams)
}
public async submitGuestbookForDatasetVersionDownload(
datasetId: number | string,
versionId: string,
guestbookResponse: GuestbookResponseDTO,
format?: string
): Promise<string> {
const endpoint = this.buildApiEndpoint(
`${this.accessResourceName}/dataset`,
`versions/${versionId}`,
datasetId
)
const queryParams = format ? { signed: true, format } : { signed: true }
return await this.submitGuestbookDownload(endpoint, guestbookResponse, queryParams)
}
private async submitGuestbookDownload(
apiEndpoint: string,
guestbookResponse: GuestbookResponseDTO,
queryParams: object
): Promise<string> {
const requestConfig = buildRequestConfig(
true,
queryParams,
ApiConstants.CONTENT_TYPE_APPLICATION_JSON
)
const response = await fetch(
this.buildUrlWithQueryParams(buildRequestUrl(apiEndpoint), queryParams),
{
method: 'POST',
headers: this.buildFetchHeaders(requestConfig.headers),
credentials: this.getFetchCredentials(requestConfig.withCredentials),
body: JSON.stringify(guestbookResponse)
}
).catch((error) => {
throw new WriteError(error instanceof Error ? error.message : String(error))
})
const responseData = await this.parseResponseBody(response)
if (!response.ok) {
throw new WriteError(this.buildFetchErrorMessage(response.status, responseData))
}
return this.getSignedUrlOrThrow(responseData)
}
private getFetchCredentials(withCredentials?: boolean): RequestCredentials | undefined {
if (ApiConfig.dataverseApiAuthMechanism === DataverseApiAuthMechanism.BEARER_TOKEN) {
return 'omit'
}
if (withCredentials) {
return 'include'
}
return undefined
}
private buildUrlWithQueryParams(requestUrl: string, queryParams: object): string {
const url = new URL(requestUrl)
Object.entries(queryParams).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value))
}
})
return url.toString()
}
private buildFetchHeaders(headers?: Record<string, unknown>): Record<string, string> {
const fetchHeaders: Record<string, string> = {}
if (!headers) {
return fetchHeaders
}
Object.entries(headers).forEach(([key, value]) => {
if (value !== undefined) {
fetchHeaders[key] = String(value)
}
})
return fetchHeaders
}
private async parseResponseBody(response: Response): Promise<any> {
const contentType = response.headers.get('content-type') ?? ''
if (contentType.includes('application/json')) {
return await response.json()
}
const responseText = await response.text()
try {
return JSON.parse(responseText)
} catch {
return responseText
}
}
private buildFetchErrorMessage(status: number, responseData: any): string {
const message =
typeof responseData === 'string'
? responseData
: responseData?.message || responseData?.data?.message || 'unknown error'
return `[${status}] ${message}`
}
private getSignedUrlOrThrow(responseData: any): string {
const signedUrl = responseData?.data?.signedUrl
if (typeof signedUrl !== 'string' || signedUrl.length === 0) {
throw new WriteError('Missing signedUrl in access download response.')
}
return signedUrl
}
}