/
Bookmark.ts
437 lines (382 loc) · 13.4 KB
/
Bookmark.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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import {
ThingPersisted,
addNamedNode,
addStringNoLocale,
addUrl,
createSolidDataset,
createThing,
getLiteral,
getNamedNode,
getPodUrlAll,
getSolidDataset,
getThing,
saveSolidDatasetAt,
setNamedNode,
setStringNoLocale,
setThing,
setUrl
} from "@inrupt/solid-client";
import { getThingAll, removeThing } from "@inrupt/solid-client";
import {
BOOKMARK,
DCTERMS,
FOAF,
RDF,
RDFS
} from "@inrupt/vocab-common-rdf";
import { namedNode } from '@rdfjs/data-model';
import { __DC_UPDATED, __crdt_createdAt, __crdt_updatedAt, __crdt_resource } from "../constants";
import { TypeIndexHelper } from "@rezasoltani/solid-typeindex-support";
import { isValidUrl } from "../utils";
/**
* Interface for the shape of a bookmark object that can be created.
* Contains title, topic, link, and creator fields.
*
*/
export type ICreateBookmark = {
title: string;
topic?: string;
link: string;
creator?: string;
};
/**
* Interface for the shape of a bookmark object that can be updated.
* Contains title, topic, link, and creator fields.
*/
export type IUpdateBookmark = {
title: string;
topic?: string;
link: string;
creator?: string;
};
/**
* Interface defining the shape of a bookmark object.
* Extends ICreateBookmark and adds url, created, and updated fields.
*/
export type IBookmark = ICreateBookmark & {
url: string;
created?: string;
updated?: string;
};
/**
* The Bookmark class provides methods for CRUD over Bookmark resources in Solid.
* @public
*/
export class Bookmark {
/**
* Gets the registry URLs for the bookmarks for the given webId.
*
* @param fetch - The fetch function to use for network requests
* @param webId - The webId of the user to get bookmark registries for
* @returns A promise resolving to an array of registry URL strings
* @internal
*/
public static async getRegisteryUrls(
fetch: typeof globalThis.fetch,
webId: string
): Promise<string[]> {
const registeries = await TypeIndexHelper.getFromTypeIndex(webId!, BOOKMARK.Bookmark, fetch, true)
if (!!registeries?.length) {
return registeries
} else {
const podToUse = (await getPodUrlAll(webId!, { fetch: fetch }))[0];
const baseURL = podToUse ? podToUse : webId?.split("/profile")[0]
const defaultIndexUrl = `${baseURL}/bookmarks/index.ttl`;
const defaultIndexDataset = await getSolidDataset(defaultIndexUrl, { fetch: fetch });
if (!defaultIndexDataset) {
await saveSolidDatasetAt(defaultIndexUrl, createSolidDataset(), { fetch: fetch });
}
await TypeIndexHelper.registerInTypeIndex(webId!, "bookmarks_registery", BOOKMARK.Bookmark, fetch, defaultIndexUrl, true)
return [defaultIndexUrl];
}
}
/**
* Gets all bookmarks for the given user's webId.
*
* @param fetch - The fetch function to use for network requests.
* @param webId - The user's webId.
* @returns A promise resolving to an array of the user's bookmarks.
*/
public static async getAll(
fetch: typeof globalThis.fetch,
webId: string
): Promise<IBookmark[]> {
const indexUrls = await this.getRegisteryUrls(fetch, webId);
try {
const all = indexUrls.map(async (indexUrl) => {
const ds = await getSolidDataset(indexUrl, { fetch: fetch });
const things = getThingAll(ds)
const bookmarks = await things.map(thing => this.mapBookmark(thing))
const resources = bookmarks.filter(Bookmark => !Bookmark.url.endsWith('-metadata'))
const metadatas = bookmarks.filter(Bookmark => Bookmark.url.endsWith('-metadata'))
const responce = resources.map(bookmark => {
const metadata = metadatas.find((meta: any) => meta.resource === bookmark.url) as any
return {
...bookmark,
...(metadata?.created && { created: metadata.created }),
...(metadata?.updated && { updated: metadata.updated }),
}
})
return responce
})
const allPromise = Promise.all([...all]);
const values = (await allPromise).flat();
return values;
} catch (error) {
return []
}
}
/**
* Gets a bookmark by URL.
*
* @param url - The URL of the bookmark to get.
* @param fetch - The fetch function to use for network requests.
* @returns A promise resolving to the bookmark, if found, or undefined.
*/
public static async get(
url: string,
fetch: typeof globalThis.fetch
): Promise<IBookmark | undefined> {
const ds = await getSolidDataset(url, { fetch: fetch });
const thing = getThing(ds, url)
const meta = getThing(ds, `${url}-metadata`)
const metadata = meta ? this.mapBookmark(meta) : undefined as any
return thing ? {
...this.mapBookmark(thing),
...(metadata?.resource === thing?.url && metadata?.created && { created: metadata?.created }),
...(metadata?.resource === thing?.url && metadata?.updated && { updated: metadata?.updated }),
} : undefined
}
/**
* Deletes the bookmark at the given URL.
*
* @param url - The URL of the bookmark to delete.
* @param fetch - The fetch function to use for network requests.
* @returns A promise resolving to true if the bookmark was deleted, false otherwise.
*/
public static async delete(
url: string,
fetch: typeof globalThis.fetch
): Promise<boolean> {
const ds = await getSolidDataset(url, { fetch: fetch });
const thing = getThing(ds, url);
if (thing) {
const updatedBookmarks = removeThing(ds, thing);
const updatedDataset = await saveSolidDatasetAt(url, updatedBookmarks, { fetch: fetch });
if (updatedDataset) {
return true
} else {
return false
}
} else {
return false
}
};
/**
* Creates a new bookmark.
*
* @param payload - The bookmark data.
* @param fetch - The fetch function.
* @param webId - The user's WebID.
* @returns A promise resolving to true if the bookmark was created, false otherwise.
*/
public static async create(
payload: ICreateBookmark,
fetch: typeof globalThis.fetch,
webId: string
): Promise<boolean> {
const { title, link, creator, topic } = payload;
if (!isValidUrl(link)) throw new Error("link is not a valid URL");
if (creator && !isValidUrl(creator))
throw new Error("creator is not a valid URL");
const [indexUrl] = await this.getRegisteryUrls(fetch, webId);
const ds = await getSolidDataset(indexUrl, { fetch: fetch });
let newBookmarkThing = createThing();
newBookmarkThing = addStringNoLocale(
newBookmarkThing,
DCTERMS.title,
title
);
newBookmarkThing = addNamedNode(
newBookmarkThing,
BOOKMARK.recalls,
namedNode(link)
);
if (creator)
newBookmarkThing = addNamedNode(
newBookmarkThing,
DCTERMS.creator,
namedNode(creator)
);
if (topic && isValidUrl(topic))
newBookmarkThing = addNamedNode(
newBookmarkThing,
BOOKMARK.hasTopic,
namedNode(topic)
);
if (topic && !isValidUrl(topic))
newBookmarkThing = addStringNoLocale(
newBookmarkThing,
BOOKMARK.hasTopic,
topic
);
newBookmarkThing = addStringNoLocale(
newBookmarkThing,
DCTERMS.created,
new Date().toISOString()
);
newBookmarkThing = addStringNoLocale(
newBookmarkThing,
__DC_UPDATED,
new Date().toISOString()
);
newBookmarkThing = addUrl(newBookmarkThing, RDF.type, BOOKMARK.Bookmark);
const updatedBookmarkList = setThing(ds, newBookmarkThing);
const updatedDataset = await saveSolidDatasetAt(
indexUrl,
updatedBookmarkList,
{ fetch: fetch }
);
return updatedDataset ? true : false;
}
/**
* Updates a bookmark resource in a Solid pod by replacing its metadata
* with the provided payload.
*
* @param url - The URL of the bookmark resource to update
* @param payload - The updated bookmark metadata
* @param fetch - The fetch function to use for network requests
* @returns The updated bookmark object if successful, else undefined
*/
public static async update(
url: string,
payload: IUpdateBookmark,
fetch: typeof globalThis.fetch
): Promise<IBookmark | undefined> {
const ds = await getSolidDataset(url, { fetch: fetch });
let thing = getThing(ds, url);
if (thing) {
const { title, link, creator, topic } = payload;
if (!isValidUrl(link)) throw new Error("link is not a valid URL");
if (creator && !isValidUrl(creator))
throw new Error("creator is not a valid URL");
thing = setStringNoLocale(thing, DCTERMS.title, title);
thing = setNamedNode(thing, BOOKMARK.recalls, namedNode(link));
if (creator)
thing = setNamedNode(thing, DCTERMS.creator, namedNode(creator));
if (topic && isValidUrl(topic))
thing = setNamedNode(thing, BOOKMARK.hasTopic, namedNode(topic));
if (topic && !isValidUrl(topic))
thing = setStringNoLocale(thing, BOOKMARK.hasTopic, topic);
thing = setStringNoLocale(thing, __DC_UPDATED, new Date().toISOString());
thing = setUrl(thing, RDF.type, BOOKMARK.Bookmark);
const updatedBookmarkList = setThing(ds, thing);
await saveSolidDatasetAt(url, updatedBookmarkList, { fetch: fetch });
return this.mapBookmark(thing);
}
}
/**
* Maps a Solid dataset Thing to a Bookmark interface.
*
* @param thing - The Thing to map
* @returns The mapped Bookmark interface
* @internal
*/
private static mapBookmark(thing: ThingPersisted): IBookmark {
const url = thing.url;
const title = this.mapTitle(thing);
const link = this.mapLink(thing);
const topic = this.mapTopic(thing);
const created = this.mapCreated(thing);
const updated = this.mapUpdated(thing);
const creator = this.mapCreator(thing);
const resource = getNamedNode(thing, __crdt_resource)?.value;
return {
url,
title,
link,
...(topic && { topic }),
...(created && { created }),
...(updated && { updated }),
...(creator && { creator }),
...(resource && { resource }),
};
}
/**
* Maps the title from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The title as a string
* @internal
*/
private static mapTitle(thing: ThingPersisted): string {
return (
getLiteral(thing, DCTERMS.title)?.value ??
getLiteral(thing, RDFS.label)?.value ??
""
);
}
/**
* Maps the link URL from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The link URL as a string
* @internal
*/
private static mapLink(thing: ThingPersisted): string {
return (
getLiteral(thing, BOOKMARK.recalls)?.value ??
getNamedNode(thing, BOOKMARK.recalls)?.value ??
""
);
}
/**
* Maps the creation date from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The creation date as a string, if available
* @internal
*/
private static mapCreated(thing: ThingPersisted): string | undefined {
return (
getLiteral(thing, DCTERMS.created)?.value ??
getLiteral(thing, __crdt_createdAt)?.value
);
}
/**
* Maps the update date from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The update date as a string, if available
* @internal
*/
private static mapUpdated(thing: ThingPersisted): string | undefined {
return (
getLiteral(thing, __DC_UPDATED)?.value ??
getLiteral(thing, __crdt_updatedAt)?.value
);
}
/**
* Maps the creator from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The creator as a string, if available
* @internal
*/
private static mapCreator(thing: ThingPersisted): string | undefined {
return (
getNamedNode(thing, DCTERMS.creator)?.value ??
getNamedNode(thing, FOAF.maker)?.value
);
}
/**
* Maps the topic from a Solid dataset Thing.
*
* @param thing - The Thing to map
* @returns The topic as a string, if available
* @internal
*/
private static mapTopic(thing: ThingPersisted): string | undefined {
return getNamedNode(thing, BOOKMARK.hasTopic)?.value;
}
}