Created
October 26, 2021 09:38
-
-
Save Ozerich/7cca394e3ce570de1494be7833c1e674 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fetch from "node-fetch"; | |
| import {atob, Blob, Buffer} from "buffer"; | |
| import FormData from 'form-data'; | |
| import Request from "./requests/Request"; | |
| import OrdersUsedByPostRequest from "./requests/OrdersUsedByPostRequest"; | |
| class AtlantmApi { | |
| protected baseUrl: string; | |
| protected apiKey: string; | |
| constructor(baseUrl: string, apiKey: string) { | |
| this.baseUrl = baseUrl; | |
| this.apiKey = apiKey; | |
| } | |
| private async post(endpoint: string, request: Request) { | |
| console.log('AtlantM API POST ' + this.baseUrl + endpoint); | |
| let body, headers = {}; | |
| const files = request.getFiles(); | |
| if (request.hasFiles()) { | |
| body = new FormData(); | |
| const requestBody = request.getRequestBody(); | |
| for (let field in request.getRequestBody()) { | |
| if (requestBody[field] !== null) { | |
| body.append(field, requestBody[field]); | |
| } | |
| } | |
| for (let field in files) { | |
| const filesField = files[field]; | |
| if (Array.isArray(filesField)) { | |
| for (let i = 0; i < filesField.length; i++) { | |
| const fileExt = filesField[i].split(',')[0].split(':')[1].split(';')[0].split('/')[1]; | |
| const fileBuffer = Buffer.from(filesField[i], 'base64'); | |
| const filename = 'image_' + (i < 10 ? '0' : '') + (i + 1) + '.' + fileExt; | |
| body.append(field + '[]', fileBuffer, {filename}) | |
| } | |
| } | |
| } | |
| } else { | |
| body = JSON.stringify(request.getRequestBody()); | |
| headers = { | |
| "Content-Type": 'application/json', | |
| Accept: "application/json", | |
| } | |
| } | |
| const response = await fetch(this.baseUrl + endpoint, { | |
| method: "POST", | |
| body: body, | |
| headers: { | |
| "X-Api-Key": this.apiKey, | |
| ...headers | |
| }, | |
| }); | |
| if (response.status === 403) { | |
| throw new Error('Неверный API ключ'); | |
| } | |
| const responseJson = await response.json(); | |
| if (response.status === 404) { | |
| throw new Error(responseJson.error.message); | |
| } | |
| if (response.status !== 200) { | |
| throw new Error('Ошибка API') | |
| } | |
| return responseJson; | |
| } | |
| async ordersUsedByPost(request: OrdersUsedByPostRequest) { | |
| return this.post('/v1/orders/usedbuy/post/', request); | |
| } | |
| } | |
| const atlantmApi = new AtlantmApi(process.env.ATLANTM_API_URL ?? '', process.env.ATLANTM_API_KEY ?? ''); | |
| export default atlantmApi; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment