-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule.js
71 lines (71 loc) · 2.49 KB
/
module.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
const mongo = require("mongoose")
module.exports = {
connect: async function(url){
if(!url)return("url is required")
await mongo.connect(url).catch((error)=>{
return console.log(error)
})
this.url = url
this.getDB = class{
constructor(name){
this.schema = new mongo.Schema({
name: String,
type: String,
value: String,
indexKey: String
}),
this.name = name
this.model = mongo.model(this.name, this.schema)
}
async set(name,value,indexKey){
if(typeof(name) !== "string")throw new Error("key must be a string")
const data = await this.dget(name) || new this.model()
if(typeof(value) === "string"){
data.name = name
data.value = JSON.stringify(value)
data.indexKey = value
}else if(typeof(value) === "number"){
data.name = name
data.value = JSON.stringify(value)
data.indexKey = String(value)
}else{
data.name = String(name)
data.value = JSON.stringify(value)
data.indexKey = indexKey || "null"
}
data.save()
}
async dget(name){
const data = await this.model.findOne({name:name})
return data
}
async get(name){
const data = await this.dget(name)
if(!data)return null
return JSON.parse(data.value)
}
async delete(name){
const data = await this.dget(name)
if(!data)return null
data.remove()
}
async dgetByIndex(name){
const data = await this.model.findOne({indexKey:name})
return data
}
async getByIndex(name){
const data = await this.dgetByIndex(name)
if(!data)return null
return JSON.parse(data.value)
}
async getAll(){
const data = await this.model.find({})
const map = new Map()
data.map(a=>{
map.set(a.name,JSON.parse(a.value))
})
return map
}
}
},
}