This repository has been archived on 2021-02-16. You can view files and clone it, but cannot push or open issues or pull requests.
Nodezzarella/lib/db/rethinkdb/db.js

113 lines
3.0 KiB
JavaScript

const r = require("rethinkdb"),
promise = require('promise'),
fs = require('fs'),
log = require("color-logs")(true, true, "RethinDB connector");
class rethinkdb{
static constructor(){
}
get(query){
return new Promise((resolve, reject) => {
/*
* select table
*/
var formatedQuery = r.table(Object.keys(query.select)[0]);
/*
* create join
*/
if(typeof query.join === "object"){
formatedQuery = formatedQuery.eqJoin(query.join.left, r.db(dbConf.dbName).table(query.join.right.db))
}
/*
* form filter / condition of qyert
*/
if(query.condition !== ""){
formatedQuery = formatedQuery.filter(query.condition);
}
/**
* select collumn of table
*/
for (var collumn in query.select){
if(query.select.hasOwnProperty(collumn)){
var selectCollumn = query.select[collumn];
break;
}
}
// r.db("nodezzarella").table("articles").eqJoin("categorie_id", r.db("nodezzarella").table("categories")).pluck({"left":["id"]})
if(selectCollumn.length > 0){
formatedQuery = formatedQuery.pluck(selectCollumn);
}
/**
* run query
*/
//log.debug(formatedQuery);
formatedQuery.run(dbConnexion).then((cursor) => {
return cursor.toArray();
}).then((result) => {
resolve(JSON.stringify(result));
}).catch((err)=>{
throw err;
log.error(err);
});
});
}
post(){
/*r.db("nodezzarella").table("categories").insert([{
"title": "global test",
"uri":"global-test",
"description":"desc"
},
{
"title": "test",
"uri":"test",
"description":"desc2"
}])*/
//https://www.rethinkdb.com/api/javascript/insert/
}
update(){
}
remove(){
}
getDBConfig(){
return new Promise((resolve, reject) => {
fs.access("./config.json", fs.constants.F_OK || fs.constants.R_OK, (error) => {
if(error){
reject(new Error("File not exist"));
}
else{
resolve(require("./config.json"));
}
});
});
}
connectDB(config){
this.host = config.host;
this.port = config.port;
this.dbName = config.dbName;
log.info("Application connecting to database...");
return r.connect({
host: config.host,
port: config.port,
db: config.dbName
});
}
}
module.exports = rethinkdb;