Repository navigation
Expand file tree
/
Copy pathdata-database.js
More file actions
70 lines (55 loc) · 2.04 KB
/
Copy pathdata-database.js
File metadata and controls
70 lines (55 loc) · 2.04 KB
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
import { MongoClient, ObjectId } from 'mongodb';
const client = new MongoClient(process.env.MONGO_URI);
await client.connect();
let db = client.db(process.env.DATABASE_NAME || 'LospecBotV4');
//exported so modules that need real collections (rather than the key/value
//document store below) can share this connection - see util/lft-store.js
export const database = db;
//check if the collection exists and create it if not
let collections = await db.listCollections().toArray();
if (!collections.find(c => c.name == 'data')) await db.createCollection('data');
let collection = db.collection('data');
collection.createIndex({ name: 1 }, { unique: true });
console.log('Using MongoDB data storage...');
class Data {
constructor(slug) {
if (!slug.match(/^[a-z-]+$/)) throw new Error('Invalid slug: "'+slug+'"');
this.slug = slug;
this.initialize();
}
async initialize() {
console.log('Initializing data store:', this.slug);
//make sure the document exists and create it if not
try {
this.store = await collection.findOne({name: this.slug});
if (!this.store) await collection.insertOne({name: this.slug});
}
catch (err) {console.error(err);}
}
get(key) {
console.log('Getting', this.slug, key);
return this.store?.[key];
}
//returns the write so callers that care can await it and report failures
set(key, value) {
console.log('Setting', this.slug, key, 'to', value);
this.store[key] = value;
return collection.updateOne({name: this.slug}, {$set: {[key]: value}});
}
keys() {
return Object.keys(this.store || {}).filter(key => key !== '_id' && key !== 'name');
}
async assert(...args) {
const required = typeof args[args.length - 1] === 'boolean' ? args.pop() : true;
const keys = args;
await this.initialize();
for (const key of keys) {
if (!this.store[key] || this.store[key] == '') {
this.store[key] = '';
await collection.updateOne({_id: this.store._id}, {$set: {[key]: ''}});
if (required) throw new Error('Key "'+key+'" is not defined in data store "'+this.slug+'"');
}
}
}
}
export default Data;