/** * Created by DICH on 5/6/2018. */ import ElasticWhereBuilder from "./ElasticWhereBuilder"; import {IElasticDao} from "../IElasticDao"; export default class ElasticUpdateBuilder extends ElasticWhereBuilder { private elasticRepos : IElasticDao private updateInfo : any = {} private isUpsert : boolean = false private useScript : boolean = false private docId constructor(repos : IElasticDao) { super() this.elasticRepos = repos } public data(info): ElasticUpdateBuilder { this.updateInfo = info return this } public upsert(isUpsert): ElasticUpdateBuilder { this.isUpsert = isUpsert return this } public increase(key, value): ElasticUpdateBuilder { this.updateInfo = {...this.updateInfo, [key]: {'$add': value}} this.useScript = true return this } public decrease(key, value): ElasticUpdateBuilder { this.updateInfo = {...this.updateInfo, [key]: {'$sub': value}} this.useScript = true return this } public id(id): ElasticUpdateBuilder { this.docId = id return this } public update(cb = null): Promise { if (this.whereClause && this.whereClause['$script']) { return new Promise((resolve, reject) => { this.elasticRepos.updateAllScript(this.whereClause, this.updateInfo, null, error => { cb && cb(error) if (error) { return reject(error) } resolve() }) }) } else if (this.useScript && !this.isUpsert) { return new Promise((resolve, reject) => { this.elasticRepos.updateScript(this.docId, this.updateInfo, error => { cb && cb(error) if (error) { return reject(error) } resolve() }) }) } else if(this.useScript && this.isUpsert) { return new Promise((resolve, reject) => { this.elasticRepos.updateOrCreateScript(this.docId, this.updateInfo, error => { cb && cb(error) if (error) { return reject(error) } resolve() }) }) } else { return new Promise((resolve, reject) => { this.elasticRepos.updateAll(this.whereClause, this.updateInfo, null, (error, count) => { if (error) { cb && cb(error) reject(error) } else { if (!count && this.isUpsert) { this.elasticRepos.create(this.updateInfo, error => { cb && cb(error) if (error) { reject(error) } else { resolve({count}) } }) } else { cb && cb(null, {count}) resolve({count}) } } }) }) } } }