forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd.ts
98 lines (84 loc) · 2.68 KB
/
add.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
import { VisitInteraction, PageAddRequest } from '.'
import normalizeUrl from '../util/encode-url-for-id'
import pipeline, { transformUrl } from './pipeline'
import { Page, FavIcon } from './models'
import { getPage } from './util'
import { PipelineReq, Dexie } from './types'
import { initErrHandler } from './storage'
/**
* Adds/updates a page + associated visit (pages never exist without either an assoc.
* visit or bookmark in current model).
*/
export const addPage = (getDb: () => Promise<Dexie>) => async ({
visits = [],
bookmark,
pageDoc,
rejectNoContent,
}: Partial<PageAddRequest>) => {
const { favIconURI, ...pageData } = await pipeline({
pageDoc,
rejectNoContent,
})
const page = new Page(pageData)
await page.loadRels(getDb)
// Create Visits for each specified time, or a single Visit for "now" if no assoc event
visits = !visits.length && bookmark == null ? [Date.now()] : visits
visits.forEach(time => page.addVisit(time))
if (bookmark != null) {
page.setBookmark(bookmark)
}
if (favIconURI != null) {
await new FavIcon({ hostname: page.hostname, favIconURI }).save(getDb)
}
await page.save(getDb)
}
export const addPageTerms = (getDb: () => Promise<Dexie>) => async (
pipelineReq: PipelineReq,
) => {
const db = await getDb()
const pageData = await pipeline(pipelineReq)
await db.transaction('rw', db.tables, async () => {
const page = new Page(pageData)
await page.loadRels(getDb)
await page.save(getDb)
})
}
/**
* Updates an existing specified visit with interactions data.
*/
export const updateTimestampMeta = (getDb: () => Promise<Dexie>) => async (
url: string,
time: number,
data: Partial<VisitInteraction>,
) => {
const db = await getDb()
const normalized = normalizeUrl(url)
await db
.transaction('rw', db.visits, () =>
db.visits
.where('[time+url]')
.equals([time, normalized])
.modify(data),
)
.catch(initErrHandler())
}
export const addVisit = (getDb: () => Promise<Dexie>) => async (
url: string,
time = Date.now(),
) => {
const matchingPage = await getPage(getDb)(url)
if (matchingPage == null) {
throw new Error(`Cannot add visit for non-existent page: ${url}`)
}
matchingPage.addVisit(time)
return matchingPage.save(getDb).catch(initErrHandler())
}
export const addFavIcon = (getDb: () => Promise<Dexie>) => async (
url: string,
favIconURI: string,
) => {
const { hostname } = transformUrl(url)
return new FavIcon({ hostname, favIconURI })
.save(getDb)
.catch(initErrHandler())
}