/
accounts.js
65 lines (57 loc) · 1.89 KB
/
accounts.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
const faunadb = require('faunadb')
const q = faunadb.query
const {
Documents,
CreateCollection,
CreateIndex,
Collection,
Exists,
If,
Index,
Delete,
Lambda,
Paginate,
Match,
Var
} = q
/* Collection */
const CreateAccountsCollection = CreateCollection({ name: 'accounts' })
/* Indexes */
const CreateIndexAllAccounts = CreateIndex({
name: 'all_accounts',
source: Collection('accounts'),
// this is the default collection index, no terms or values are provided
// which means the index will sort by reference and return only the reference.
serialized: true
})
const CreateIndexAccountsByEmail = CreateIndex({
name: 'accounts_by_email',
source: Collection('accounts'),
// We will search on email
terms: [
{
field: ['data', 'email']
}
],
// if no values are added, the index will just return the reference.
// Prevent that accounts with duplicate e-mails are made.
// uniqueness works on the combination of terms/values
unique: true,
serialized: true
})
async function createAccountCollection(client) {
await client.query(If(Exists(Collection('accounts')), true, CreateAccountsCollection))
await client.query(If(Exists(Index('accounts_by_email')), true, CreateIndexAccountsByEmail))
await client.query(If(Exists(Index('all_accounts')), true, CreateIndexAllAccounts))
}
async function deleteAccountsCollection(client) {
await client.query(If(Exists(Collection('accounts')), Delete(Collection('accounts')), true))
await client.query(If(Exists(Index('accounts_by_email')), Delete(Index('accounts_by_email')), true))
await client.query(If(Exists(Index('all_accounts')), Delete(Delete('all_accounts')), true))
}
const DeleteAllAccounts = If(
Exists(Collection('accounts')),
q.Map(Paginate(Documents(Collection('accounts'))), Lambda('ref', Delete(Var('ref')))),
true
)
export { createAccountCollection, deleteAccountsCollection, DeleteAllAccounts }