-
Notifications
You must be signed in to change notification settings - Fork 0
/
objects.js
54 lines (44 loc) · 1.22 KB
/
objects.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
import db from "./db.js"
import canonicalize from './canonicalize.js'
import sha256 from 'sha256'
import { logger, colorizeObjectManager } from './logger.js'
export class ObjectManager {
requestObject
constructor(requestObject) {
this.requestObject = requestObject
this.getObject = this.getObject.bind(this)
}
getObjectHash(object) {
let objectHash = canonicalize(object)
objectHash = sha256(objectHash)
return objectHash
}
async getObject(objectId) {
let object
try {
object = await db.get(`object/${objectId}`)
} catch {
return await this.requestObject(objectId)
}
object = JSON.parse(object)
return object
}
async addObject(object) {
const objectId = this.getObjectHash(object)
if (await this.getObject(objectId)) {
this.logger(`Object with id ${objectId} already exists and cannot be added`)
return false
}
try {
await db.put(`object/${objectId}`, JSON.stringify(object))
this.logger(`Added object: ${objectId}`)
} catch {
this.logger(`Error adding object: ${objectId}`)
return false
}
return true
}
logger(message, ...args) {
logger.info(`${colorizeObjectManager()}: ${message}`, ...args)
}
}