/
index.js
107 lines (99 loc) · 2.41 KB
/
index.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
const { randomUUID } = require('node:crypto')
const { Level } = require('level')
var charwise = require('charwise')
var Transactor = require('level-fact-base')
const db = new Level('db', {
keyEncoding: charwise, // or any codec for sorted arrays of flat json values
valueEncoding: 'json'
})
// define a schema for attributes
// like datomic schema is stored and versioned inside the database
var schema = {
user_name: { type: 'String' },
user_email: { type: 'String' },
blogpost_text: { type: 'String' },
comment_blogpostId: { type: 'EntityID' },
comment_userId: { type: 'EntityID' },
comment_text: { type: 'String' }
// ...
}
var tr = Transactor(db, schema)
async function main () {
// create some test data
// + 2 users
// + a blog post
// + 3 comments
var fb = await tr.transact([
{
$e: 'user0', // in the real world you'll provide a unique id using something like UUID
user_name: 'foo',
user_email: 'foo@example.com'
},
{
$e: 'user1',
user_name: 'bar',
user_email: 'bar@example.com'
},
{
$e: 'post0',
blogpost_text: 'some blog post... no so long'
},
{
$e: randomUUID(),
comment_userId: 'user0',
comment_blogpostId: 'post0',
comment_text: 'This article sucks!'
},
{
$e: randomUUID(),
comment_userId: 'user1',
comment_blogpostId: 'post0',
comment_text: 'Why? I think this article is life-changing!'
},
{
$e: randomUUID(),
comment_userId: 'user0',
comment_blogpostId: 'post0',
comment_text: 'im just a troll'
}
])
// Read an entity
console.log(await fb.get('user0'))
/*
{ '$e': 'user0',
user_email: 'foo@example.com',
user_name: 'foo'
}
*/
// Get user0's comments
console.log(await fb.q(
[
['?cid', 'comment_userId', '?uid'],
['?cid', 'comment_text', '?text']
],
{ uid: 'user0' },
['text']
))
/*
[ { text: 'This article sucks!' },
{ text: 'im just a troll' }
]
*/
// Get name+email of those who commented on post0
console.log(await fb.q(
[
['?cid', 'comment_blogpostId', '?postId'],
['?cid', 'comment_userId', '?uid'],
['?uid', 'user_name', '?name'],
['?uid', 'user_email', '?email']
],
{ postId: 'post0' },
['name', 'email']
))
/*
[ { name: 'foo', email: 'foo@example.com' },
{ name: 'bar', email: 'bar@example.com' }
]
*/
}
main()