2020-11-26 17:46:36 +01:00
|
|
|
const { MongoClient } = require("mongodb")
|
2021-01-13 19:29:51 +01:00
|
|
|
const { FIELD_TYPES, QUERY_TYPES } = require("./Integration")
|
2020-11-26 17:46:36 +01:00
|
|
|
|
2021-01-11 18:18:22 +01:00
|
|
|
const SCHEMA = {
|
2021-01-15 18:29:46 +01:00
|
|
|
docs: "https://github.com/mongodb/node-mongodb-native",
|
2021-01-11 18:18:22 +01:00
|
|
|
datasource: {
|
|
|
|
connectionString: {
|
2021-01-13 19:29:51 +01:00
|
|
|
type: FIELD_TYPES.STRING,
|
2021-01-11 18:18:22 +01:00
|
|
|
required: true,
|
2021-01-15 14:42:14 +01:00
|
|
|
default: "mongodb://localhost:27017",
|
2021-01-11 18:18:22 +01:00
|
|
|
},
|
|
|
|
db: {
|
2021-01-13 19:29:51 +01:00
|
|
|
type: FIELD_TYPES.STRING,
|
2021-01-11 18:18:22 +01:00
|
|
|
required: true,
|
|
|
|
},
|
|
|
|
collection: {
|
2021-01-13 19:29:51 +01:00
|
|
|
type: FIELD_TYPES.STRING,
|
2021-01-11 18:18:22 +01:00
|
|
|
required: true,
|
|
|
|
},
|
2020-11-26 17:46:36 +01:00
|
|
|
},
|
|
|
|
query: {
|
2021-01-13 17:39:47 +01:00
|
|
|
create: {
|
2021-01-22 13:22:28 +01:00
|
|
|
type: QUERY_TYPES.JSON,
|
2021-01-13 17:39:47 +01:00
|
|
|
},
|
|
|
|
read: {
|
2021-01-22 13:22:28 +01:00
|
|
|
type: QUERY_TYPES.JSON,
|
2021-01-11 18:18:22 +01:00
|
|
|
},
|
2020-11-26 17:46:36 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
class MongoIntegration {
|
|
|
|
constructor(config) {
|
|
|
|
this.config = config
|
|
|
|
this.client = new MongoClient(config.connectionString)
|
|
|
|
}
|
|
|
|
|
|
|
|
async connect() {
|
|
|
|
return this.client.connect()
|
|
|
|
}
|
|
|
|
|
2021-01-13 17:39:47 +01:00
|
|
|
async create(query) {
|
|
|
|
try {
|
|
|
|
await this.connect()
|
|
|
|
const db = this.client.db(this.config.db)
|
|
|
|
const collection = db.collection(this.config.collection)
|
2021-01-15 14:11:51 +01:00
|
|
|
const result = await collection.insertOne(query.json)
|
2021-01-13 17:39:47 +01:00
|
|
|
return result
|
|
|
|
} catch (err) {
|
2021-01-15 14:11:51 +01:00
|
|
|
console.error("Error writing to mongodb", err)
|
2021-01-13 17:39:47 +01:00
|
|
|
throw err
|
|
|
|
} finally {
|
|
|
|
await this.client.close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async read(query) {
|
2020-11-26 17:46:36 +01:00
|
|
|
try {
|
2021-01-13 17:39:47 +01:00
|
|
|
await this.connect()
|
2020-11-26 17:46:36 +01:00
|
|
|
const db = this.client.db(this.config.db)
|
|
|
|
const collection = db.collection(this.config.collection)
|
2021-01-15 14:11:51 +01:00
|
|
|
const result = await collection.find(query.json).toArray()
|
2020-11-26 17:46:36 +01:00
|
|
|
return result
|
2020-11-26 22:23:20 +01:00
|
|
|
} catch (err) {
|
|
|
|
console.error("Error querying mongodb", err)
|
|
|
|
throw err
|
2020-11-26 17:46:36 +01:00
|
|
|
} finally {
|
|
|
|
await this.client.close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2021-01-11 18:18:22 +01:00
|
|
|
schema: SCHEMA,
|
2020-11-26 17:46:36 +01:00
|
|
|
integration: MongoIntegration,
|
|
|
|
}
|