"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Database=void 0;const faas_db_builder_1=require("@alipay/faas-db-builder"),faas_common_sdk_1=require("@alipay/faas-common-sdk"),requester_1=require("../requester"),Collection_1=require("./Collection"),Transaction_1=require("./Transaction");class Database{#t;command;Geo;#r;#e;constructor(t){this.#t=t,this.command=new faas_db_builder_1.Command,this.Geo=new faas_db_builder_1.Geo,this.#r=new faas_db_builder_1.MongoBuilder,this.#e=requester_1.Httpclient.createDatabaseHttpclient(t)}RegExp(t){return new faas_db_builder_1.Regex(t)}regexp(t){return new faas_db_builder_1.Regex(t)}regex(t){return new faas_db_builder_1.Regex(t)}collection(t){if(!t)throw faas_common_sdk_1.FaasError.INVALID_PARAM_ERR("collectionName","\u4E0D\u80FD\u4E3A\u7A7A");return new Collection_1.Collection(this.#t,t,this.#e)}#n(){return`/${this.#t.functionDatabaseName||"faas"}`}#a(t){return`${this.#n()}/${t}`}async requestRaw(t,e,s,a){const{res:r}=await this.#e.requestRaw({method:t,path:e,data:s,headers:a});return r}async createCollection(t){if(this.#t.ignoreCollectionExists){const a=await this.#i(t);if(a)return a}const e="PUT",s=this.#a(t);return await this.#s(e,s)}async getCollection(t){const e="GET",s=this.#a(t);return await this.#s(e,s)}async listCollection(t,e){const s="POST",a=`${this.#n()}?list`,{options:r}=this.#r.listCollection(t,e);return await this.#s(s,a,r)}async deleteCollection(t){const e="DELETE",s=this.#a(t);return await this.#s(e,s)}async startTransaction(){return await Transaction_1.Transaction.create(this.#t,this.#e)}async runTransaction(t){const e=await this.startTransaction();try{const s=await t(e);if(e.isRollback())throw e.reason;return e.isProcessing()&&await e.commit(),s}catch(s){if(e.isProcessing())try{await e.rollback(s)}catch(a){throw a.cause=s,a}throw e.isRollback()?e.reason:s}}async#i(t){try{return await this.getCollection(t)}catch(e){if(e.httpStatus===404)return null;throw e}}async#s(t,e,s){const a=await this.#e.request({method:t,path:e,data:s});return faas_common_sdk_1.ResponseUtil.handleResponse(a)}}exports.Database=Database;