-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtools.js
91 lines (81 loc) · 2.27 KB
/
tools.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
const mongo = require('mongodb')
const ObjectId = mongo.ObjectId
require('dotenv').config()
const { DB_URL, DB_NAME } = process.env
const command = process.argv[2]
const params = process.argv.slice(3)
const openConnection = () => mongo.MongoClient.connect(DB_URL, { useNewUrlParser: true })
.then(client => Promise.all([
client.db(DB_NAME),
Promise.resolve(client),
]))
const generateToken = value => {
if (value && value !== 'none') return Promise.resolve(value)
const chars = 'abcdefghijklmnopqrstuvwxyz1234567890'
const result = []
for (let i=0; i<64; i++) {
const index = Math.floor(Math.random() * chars.length)
result.push(chars[index])
}
return Promise.resolve(result.join(''))
}
const show = ([ name='users' ]) => openConnection()
.then(([ db, client ]) => Promise.all([
db.collection(name).find({}).toArray(),
Promise.resolve(client),
]))
.then(([ items, client ]) => {
console.log(JSON.stringify(items, null, 4))
client.close()
})
const create_token = ([ token, ...groups ]) => Promise.all([
openConnection(),
generateToken(token),
])
.then(([[ db, client ], token ]) => Promise.all([
Promise.resolve(client),
Promise.resolve(token),
db.collection('invites').insertOne({ token, groups: groups.length > 0 ? groups : [ '1' ]}),
]))
.then(([ client, token ]) => {
console.log(token)
client.close()
})
const insert = ([ collection, document ]) =>
openConnection()
.then(([ db, client ]) =>
Promise.all([
Promise.resolve(client),
db.collection(collection).insertOne(JSON.parse(document))
])
)
.then(([ client, data ]) => {
console.log(data.insertedId)
client.close()
})
const reset = (names) => openConnection()
.then(([ db, client ]) => Promise.all([
Promise.resolve(client),
...names.map(x => db.collection(x).deleteMany({})),
]))
.then(([ client ]) => {
console.log(`Cleared collections [${names}].`)
client.close()
})
const remove = ([ collection, id ]) => openConnection()
.then(([ db, client ]) => Promise.all([
Promise.resolve(client),
db.collection(collection).findOneAndDelete({ _id: ObjectId(id) })
]))
.then(([ client, removed]) => {
console.log(`Removed element ${id} from ${collection}`)
client.close()
})
const commands = {
create_token,
remove,
reset,
show,
insert,
}
commands[command](params)