/
upsertResource.ts
75 lines (73 loc) · 2.28 KB
/
upsertResource.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
import { IUserRequestOptions } from "@esri/arcgis-rest-auth";
import { addItemResource, updateItemResource } from "@esri/arcgis-rest-portal";
import HubError from "../HubError";
import { objectToJsonBlob, stringToBlob, doesResourceExist } from ".";
import { getPortalApiUrl } from "../urls";
/**
* Given an item, and owner, Search for if the resource exists
* and if does, update it, otherwise add it. Returns a url for the item.
*
* @export
* @param {string} id
* @param {string} owner
* @param {*} resource
* @param {string} name
* @param {IUserRequestOptions} ro
* @param {string} [prefix=""]
* @return {*} {Promise<string>}
*/
export async function upsertResource(
id: string,
owner: string,
resource: any,
name: string,
ro: IUserRequestOptions,
prefix: string = ""
): Promise<string> {
try {
const extension = name.split(".").pop();
// Search against the item resources to see if the resource exists
const doesResExist: boolean = await doesResourceExist(id, name, ro);
// if the resource exists, update it, otherwise add it
const resourceFunc = doesResExist ? updateItemResource : addItemResource;
// JSON and text resources have....odd things happen
// to them when they are added as resources and NOT
// converted to blobs. Thus we convert them to blobs
let resourceToUpload = resource;
if (extension === "json") {
resourceToUpload = objectToJsonBlob(resource);
}
if (extension === "txt") {
resourceToUpload = stringToBlob(resource);
}
// Add item resource
const response = await resourceFunc({
id,
owner,
resource: resourceToUpload,
name,
prefix,
...ro,
});
// if err throw
if (!response.success) {
throw new HubError(
"Add Item Resource",
`Error adding resource ${name} to item ${id}.`
);
}
// return url
const portalRestUrl = getPortalApiUrl(ro.portal);
const _prefix = prefix ? `${prefix}/` : "";
return `${portalRestUrl}/content/items/${id}/resources/${_prefix}${name}`;
} catch (err) {
if (err instanceof Error) {
throw new HubError("Add Item Resource", err.message, err);
} else {
throw new HubError(
"Add Item Resource",
`Error adding resource ${name} to item ${id}.`
);
}
}
}