letterxpress/ts/letterxpress.classes.account.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-11-16 16:54:45 +00:00
import * as plugins from './letterxpress.plugins';
2019-11-22 14:02:56 +00:00
import { response } from 'express';
2019-11-16 16:54:45 +00:00
export interface ILetterXpressConstructorOptions {
2019-11-22 14:02:56 +00:00
username: string;
apiKey: string;
}
2019-11-16 16:54:45 +00:00
export class LetterXpressAccount {
2019-11-22 14:02:56 +00:00
public baseApiUrl = 'https://api.letterxpress.de/v1';
public options: ILetterXpressConstructorOptions;
2019-11-21 14:01:41 +00:00
public letterSentObservable = new plugins.smartrx.rxjs.Subject<plugins.smartletter.Letter>();
constructor(optionsArg: ILetterXpressConstructorOptions) {
this.options = optionsArg;
}
2019-11-21 14:01:41 +00:00
/**
* sends a letter
* @param letterArg
*/
public async sendLetter(letterArg: plugins.smartletter.Letter) {
const letterPdfResult = await letterArg.getPdfResult();
2019-11-22 14:02:56 +00:00
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;
2019-11-21 14:01:41 +00:00
}
/**
* fires the request
*/
2019-11-22 14:02:56 +00:00
private async request(routeArg: string, methodArg: 'GET' | 'POST' | 'DELETE', payload: any = {}) {
const requestUrl = `${this.baseApiUrl}${routeArg}`;
console.log(requestUrl);
2019-11-21 14:01:41 +00:00
const requestData = {
auth: {
2019-11-22 14:02:56 +00:00
username: this.options.username,
2019-11-21 14:01:41 +00:00
apikey: this.options.apiKey
},
...payload
};
2019-11-22 14:02:56 +00:00
const response = await plugins.smartrequest.request(requestUrl, {
2019-11-21 14:01:41 +00:00
method: methodArg,
headers: {
'Content-Type': 'application/json'
},
requestBody: JSON.stringify(requestData)
});
2019-11-22 14:02:56 +00:00
console.log(response.body);
return response;
2019-11-21 14:01:41 +00:00
}
}