Skip to content

Instantly share code, notes, and snippets.

@4lg4
Created February 26, 2018 22:29
Show Gist options
  • Save 4lg4/fef459da804f88616b128974a70e92e2 to your computer and use it in GitHub Desktop.
Save 4lg4/fef459da804f88616b128974a70e92e2 to your computer and use it in GitHub Desktop.
Node.js: Aerospike simple wrap using promises
/**
* Created by www.Alga.me on 12/7/17.
*
* # npm install aerospike
*/
import aerospike from 'aerospike'
export default class Aerospike {
constructor(props = {}) {
this.props = props;
this.isConnected = false;
}
createConnection() {
if(this.isConnected) {
return Promise.resolve();
}
this.aerospike = aerospike;
this.filter = aerospike.filter;
this.client = this.aerospike.client({
'hosts': this.props.connection,
policies: {
key: 1
}
});
return new Promise((resolve,reject)=> {
this.client.connect((err) => {
if (err) {
return reject(err);
}
this.isConnected = true;
resolve();
});
});
}
disconnect(){
this.client.close();
}
testConnection(){
return Promise.resolve()
.then(()=>this.createConnection())
.then(()=>this.isConnected)
}
setSet(set){
this.props.set = set;
}
key(key){
return new this.aerospike.Key(this.props.namespace, this.props.set, key);
}
put(id, rec){
const key = this.key(id);
return new Promise((resolve,reject)=>{
this.client.put(key, rec, (err) => {
if (err) {
return reject(err);
}
resolve();
})
});
}
createWithKey(key, rec){
return new Promise((resolve,reject)=>{
this.client.put(key, rec, (err) => {
if (err) {
return reject(err);
}
resolve();
})
});
}
destroy(id){
const key = this.key(id);
return new Promise((resolve,reject)=>{
this.client.remove(key, (err) => {
if (err) {
return reject(err);
}
resolve();
})
});
}
scan(options) {
Object.assign({
concurrent: true,
nobins: false
}, options);
return new Promise((resolve,reject)=>{
const scan = this.client.scan(this.props.namespace, this.props.set);
scan.concurrent = true;
scan.nobins = false;
let recordCount = 0;
let recordsArray = [];
const stream = scan.foreach();
stream.on('data', function (record,a,key,c,d) {
recordCount++;
recordsArray.push({
key,
record
})
});
stream.on('error', function (error) {
reject(error);
});
stream.on('end', function (record,a,b) {
resolve(recordsArray);
});
});
}
query(filters) {
return new Promise((resolve,reject)=>{
const scan = this.client.query(this.props.namespace, this.props.set, { filters });
let recordCount = 0;
let recordsArray = [];
const stream = scan.foreach();
stream.on('data', function (record,a,key,c,d) {
recordCount++;
recordsArray.push({
key,
record
})
});
stream.on('error', function (error) {
reject(error);
});
stream.on('end', function (record,a,b) {
resolve(recordsArray);
});
});
}
read(id){
const key = this.key(id);
return new Promise((resolve,reject)=> {
this.client.get(key, function (error, record, metadata) {
if (error) {
reject(error);
}
resolve(record);
})
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment