-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsinopiaApi.js
276 lines (250 loc) · 8.38 KB
/
sinopiaApi.js
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2019 Stanford University see LICENSE for license
import { datasetFromJsonld, jsonldFromDataset } from "utilities/Utilities"
import Config from "Config"
/* eslint-disable node/no-unpublished-import */
import {
hasFixtureResource,
getFixtureResource,
getFixtureResourceVersions,
getFixtureResourceRelationships,
} from "../__tests__/testUtilities/fixtureLoaderHelper"
import GraphBuilder from "GraphBuilder"
import { v4 as uuidv4 } from "uuid"
import rtLiteralPropertyAttrs from "../static/templates/rt_literal_property_attrs_doc.json"
import rtLookupPropertyAttrs from "../static/templates/rt_lookup_property_attrs_doc.json"
import rtPropertyTemplate from "../static/templates/rt_property_template_doc.json"
import rtResourcePropertyAttrs from "../static/templates/rt_resource_property_attrs_doc.json"
import rtResourceRemplate from "../static/templates/rt_resource_template_doc.json"
import rtUriPropertyAttrs from "../static/templates/rt_uri_property_attrs_doc.json"
import {
checkResp,
getJsonData,
getJson,
isTemplate,
templateIdFor,
getJwt,
} from "./utilities/SinopiaApiHelper"
const baseTemplates = {
"sinopia:template:property:literal": rtLiteralPropertyAttrs,
"sinopia:template:property:lookup": rtLookupPropertyAttrs,
"sinopia:template:property": rtPropertyTemplate,
"sinopia:template:property:resource": rtResourcePropertyAttrs,
"sinopia:template:resource": rtResourceRemplate,
"sinopia:template:property:uri": rtUriPropertyAttrs,
}
/**
* Fetches a resource from the Sinopia API.
* @return {Promise{[rdf.Dataset, Object]} resource as dataset, response JSON.
* @throws when error occurs retrieving or parsing the resource template.
*/
export const fetchResource = (
uri,
{ isTemplate = false, version = null } = {}
) => {
const fetchUri = encodeURI(version ? `${uri}/version/${version}` : uri)
let fetchPromise
// Templates have special handling when using fixtures.
// A template will raise when found; other resources will try API.
// Note that ignoring version of fixtures.
if (Config.useResourceTemplateFixtures && hasFixtureResource(uri)) {
try {
fetchPromise = Promise.resolve(getFixtureResource(uri))
} catch (err) {
fetchPromise = Promise.reject(err)
}
} else if (isBaseTemplateUri(uri)) {
fetchPromise = loadBaseTemplate(uri)
} else if (Config.useResourceTemplateFixtures && isTemplate) {
fetchPromise = Promise.reject(new Error("Not found"))
} else {
fetchPromise = fetch(fetchUri, {
headers: { Accept: "application/json" },
}).then((resp) => checkResp(resp).then(() => resp.json()))
}
return fetchPromise
.then((response) =>
Promise.all([datasetFromJsonld(response.data), Promise.resolve(response)])
)
.catch((err) => {
throw new Error(`Error parsing resource: ${err.message || err}`)
})
}
const isBaseTemplateUri = (uri) =>
uri.startsWith(`${Config.sinopiaApiBase}/resource/sinopia:template:`)
const loadBaseTemplate = (uri) => {
const templateId = uri.slice(`${Config.sinopiaApiBase}/resource/`.length)
const template = baseTemplates[templateId]
// Insert the expected URI for base subject.
const baseNode = template.find((node) => node["@id"] === templateId)
if (baseNode) baseNode["@id"] = uri
return Promise.resolve({ data: template })
}
export const fetchResourceVersions = (uri) => {
if (Config.useResourceTemplateFixtures && hasFixtureResource(uri)) {
return Promise.resolve(getFixtureResourceVersions())
}
return getJson(`${uri}/versions`).then((json) => json.versions)
}
export const fetchResourceRelationships = (uri) => {
if (Config.useResourceTemplateFixtures && hasFixtureResource(uri)) {
return Promise.resolve(getFixtureResourceRelationships())
}
return getJson(`${uri}/relationships`)
}
// Fetches list of groups
export const getGroups = () => getJsonData(`${Config.sinopiaApiBase}/groups`)
// Publishes (saves) a new resource
export const postResource = (resource, currentUser, group, editGroups) => {
const newResource = { ...resource }
// Mint a uri. Resource templates use the template id.
const resourceId = isTemplate(resource) ? templateIdFor(resource) : uuidv4()
const uri = `${Config.sinopiaApiBase}/resource/${resourceId}`
newResource.uri = uri
newResource.group = group
newResource.editGroups = editGroups
return putResource(newResource, currentUser, group, editGroups, "POST").then(
() => uri
)
}
// Saves an existing resource
export const putResource = (resource, currentUser, group, editGroups, method) =>
saveBodyForResource(resource, currentUser.username, group, editGroups).then(
(body) =>
getJwt().then((jwt) =>
fetch(resource.uri, {
method: method || "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${jwt}`,
},
body,
}).then((resp) => checkResp(resp).then(() => true))
)
)
export const postMarc = (resourceUri) => {
const url = resourceUri.replace("resource", "marc")
return getJwt()
.then((jwt) =>
fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
},
})
)
.then((resp) =>
checkResp(resp).then(() => resp.headers.get("Content-Location"))
)
}
export const getMarcJob = (marcJobUrl) =>
fetch(marcJobUrl).then((resp) =>
checkResp(resp).then(() => {
// Will return 200 if job is not yet completed.
// Will return 303 if job completed. Fetch automatically redirects,
// which retrieves the MARC text.
if (!resp.redirected) return [undefined, undefined]
return resp.text().then((body) => [resp.url, body])
})
)
export const getMarc = (marcUrl, asText) =>
fetch(marcUrl, {
headers: {
Accept: asText ? "text/plain" : "application/marc",
},
}).then((resp) => checkResp(resp).then(() => resp.blob()))
export const fetchUser = (userId) =>
fetch(userUrlFor(userId), {
headers: {
Accept: "application/json",
},
}).then((resp) => {
if (resp.status === 404) return postUser(userId)
return checkResp(resp).then(() => resp.json())
})
const postUser = (userId) =>
getJwt().then((jwt) =>
fetch(userUrlFor(userId), {
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
},
}).then((resp) => checkResp(resp).then(() => resp.json()))
)
export const putUserHistory = (
userId,
historyType,
historyItemKey,
historyItemPayload
) => {
const url = `${userUrlFor(userId)}/history/${historyType}/${encodeURI(
historyItemKey
)}`
return getJwt().then((jwt) =>
fetch(url, {
method: "PUT",
headers: {
Authorization: `Bearer ${jwt}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ payload: historyItemPayload }),
}).then((resp) => checkResp(resp).then(() => resp.json()))
)
}
export const postTransfer = (resourceUri, group, target) => {
const url = `${resourceUri.replace(
"resource",
"transfer"
)}/${group}/${target}`
return getJwt()
.then((jwt) =>
fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
},
})
)
.then((resp) => checkResp(resp))
}
const userUrlFor = (userId) =>
`${Config.sinopiaApiBase}/user/${encodeURI(userId)}`
const saveBodyForResource = (resource, user, group, editGroups) => {
const dataset = new GraphBuilder(resource).graph
return jsonldFromDataset(dataset).then((jsonld) =>
JSON.stringify({
data: jsonld,
user,
group,
editGroups,
templateId: resource.subjectTemplate.id,
types: [resource.subjectTemplate.class],
bfAdminMetadataRefs: resource.bfAdminMetadataRefs,
sinopiaLocalAdminMetadataForRefs: resource.localAdminMetadataForRefs,
bfItemRefs: resource.bfItemRefs,
bfInstanceRefs: resource.bfInstanceRefs,
bfWorkRefs: resource.bfWorkRefs,
})
)
}
export const detectLanguage = (text) => {
if (Config.useResourceTemplateFixtures) {
return Promise.resolve([
{
language: "en",
score: 0.9719234108924866,
},
])
}
return getJwt().then((jwt) =>
fetch(`${Config.sinopiaApiBase}/helpers/langDetection`, {
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
"Content-Type": "text/plain",
},
body: text,
})
.then((resp) => checkResp(resp).then(() => resp.json()))
.then((json) => json.data)
)
}