UNPKG

@digital-gov-mg/nui-federation-ts-sdk

Version:

This TypeScript SDK connects to the NUI Federation API for getting or creating, revoke, generating batch for NUI from the API

2 lines (1 loc) 2.3 kB
import*as e from"axios";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)({}).hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},t.apply(null,arguments)}const s=({baseUrl:t,clientId:s,clientSecret:r})=>e.default.post(`${t}/sytems/token`,{clientId:s,clientSecret:r});class r{constructor(t,r,n){if(this.baseUrl=void 0,this.clientId=void 0,this.clientSecret=void 0,this.instance=void 0,this.accessToken=null,this.isAlreadyFetchingAccessToken=!1,this.baseUrl=t,this.clientId=r,this.clientSecret=n,!t||!r||!n)throw new Error("Please provide all required configuration parameters");this.accessToken||s({baseUrl:this.baseUrl,clientId:this.clientId,clientSecret:this.clientSecret}).then(e=>{this.accessToken=e.data.accessToken}).catch(e=>console.error(e)),this.instance=e.default.create({baseURL:this.baseUrl,headers:{"Content-Type":"application/json"}})}async request({url:e,options:r}){var n=this;this.instance.interceptors.request.use(e=>(this.accessToken&&(e.headers.Authorization=`Bearer ${this.accessToken}`),e),e=>Promise.reject(e)),this.instance.interceptors.response.use(e=>e,async function(e){if(!e.response)return Promise.reject(e);const{config:t,response:r}=e,i=t;if((401===r.status||403===r.status)&&!i._retry){if(i._retry=!0,!n.isAlreadyFetchingAccessToken){n.isAlreadyFetchingAccessToken=!0;try{const e=await s({baseUrl:n.baseUrl,clientId:n.clientId,clientSecret:n.clientSecret});n.accessToken=e.data.accessToken}catch(e){return Promise.reject(e)}finally{n.isAlreadyFetchingAccessToken=!1}}return i.headers.Authorization=`Bearer ${n.accessToken}`,n.instance(i)}return Promise.reject(e)});try{return(await this.instance.request(t({url:e},r))).data}catch(e){var i;const t=(null==(i=e.response)||null==(i=i.data)?void 0:i.message)||e.message||"An error occurred while sending request";throw new Error(t)}}}class n extends r{async getOrCreateUIN(e){return this.request({url:"/uins",options:{method:"PUT",data:e}})}async revokeUIN(e){return this.request({url:`/uins/${e}/revoke`,options:{method:"DELETE"}})}async generateBatchUIN(e){return this.request({url:"/uins/batch",options:{method:"POST",params:{count:e}}})}}class i{constructor(e,t,s){this.uin=void 0,this.uin=new n(e,t,s)}}export{i as NuiFederation};