letterxpress/ts/letterxpress.classes.account.ts
2019-11-22 14:02:56 +00:00

76 lines
2.2 KiB
TypeScript

import * as plugins from './letterxpress.plugins';
import { response } from 'express';
export interface ILetterXpressConstructorOptions {
username: string;
apiKey: string;
}
export class LetterXpressAccount {
public baseApiUrl = 'https://api.letterxpress.de/v1';
public options: ILetterXpressConstructorOptions;
public letterSentObservable = new plugins.smartrx.rxjs.Subject<plugins.smartletter.Letter>();
constructor(optionsArg: ILetterXpressConstructorOptions) {
this.options = optionsArg;
}
/**
* sends a letter
* @param letterArg
*/
public async sendLetter(letterArg: plugins.smartletter.Letter) {
const letterPdfResult = await letterArg.getPdfResult();
const response = await this.request('/setJob', 'POST', {
letter: {
base64_file: letterPdfResult.buffer.toString('base64'),
base64_checksum: await plugins.smarthash.md5FromString(
letterPdfResult.buffer.toString('base64')
),
specification: {
color: '4',
mode: 'simplex',
ship: letterArg.options.to.country === 'Germany' ? 'national' : 'international'
}
}
});
letterArg.setProcessingId(response.body.letter.job_id);
return letterArg;
}
public async cancelLetter(letterArg: plugins.smartletter.Letter) {
const processingId = letterArg.getProcessingId();
return await this.cancelLetterByProcessingId(processingId);
}
public async cancelLetterByProcessingId(processingId: string) {
const response = await this.request(`/deleteJob/${processingId}`, 'DELETE');
return response;
}
/**
* fires the request
*/
private async request(routeArg: string, methodArg: 'GET' | 'POST' | 'DELETE', payload: any = {}) {
const requestUrl = `${this.baseApiUrl}${routeArg}`;
console.log(requestUrl);
const requestData = {
auth: {
username: this.options.username,
apikey: this.options.apiKey
},
...payload
};
const response = await plugins.smartrequest.request(requestUrl, {
method: methodArg,
headers: {
'Content-Type': 'application/json'
},
requestBody: JSON.stringify(requestData)
});
console.log(response.body);
return response;
}
}