nest-square
Version:
NestJS module for Square Node.js SDK
153 lines • 7.72 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var NestSquareService_1;
import { HttpStatus, Inject, Injectable, InternalServerErrorException, Logger, } from "@nestjs/common";
import pRetry from "p-retry";
import { ApiError, Client, FileWrapper, } from "square";
import { Readable } from "stream";
import { NEST_SQUARE_CONFIG_INJECTION_KEY, } from "./nest-square.config.js";
let NestSquareService = NestSquareService_1 = class NestSquareService {
constructor(config) {
this.config = config;
this.logger = new Logger(NestSquareService_1.name);
this.logger.verbose(this.constructor.name);
}
client(params) {
this.logger.verbose(this.client.name);
return new Client({
accessToken: params === null || params === void 0 ? void 0 : params.accessToken,
environment: this.config.clientEnvironment,
});
}
retryOrThrow(accessToken, clientFn) {
this.logger.verbose(this.retryOrThrow.name);
return this.pRetryOrThrow(() => clientFn(this.client({ accessToken: accessToken })));
}
retryObtainTokenOrThrow(params) {
const { code } = params;
this.logger.verbose(this.retryObtainTokenOrThrow.name);
return this.pRetryOrThrow(() => this.client().oAuthApi.obtainToken({
clientId: this.config.oauthClientId,
clientSecret: this.config.oauthClientSecret,
grantType: "authorization_code",
code,
}));
}
retryRevokeTokenOrThrow(params) {
const { accessToken, merchantId, revokeOnlyAccessToken } = params;
this.logger.verbose(this.retryObtainTokenOrThrow.name);
return this.pRetryOrThrow(() => this.client().oAuthApi.revokeToken({
clientId: this.config.oauthClientId,
accessToken,
merchantId,
revokeOnlyAccessToken,
}, `Authorization: Client ${this.config.oauthClientSecret}`));
}
retryRefreshTokenOrThrow(params) {
return __awaiter(this, void 0, void 0, function* () {
const { refreshToken } = params;
this.logger.verbose(this.retryRefreshTokenOrThrow.name);
return this.pRetryOrThrow(() => this.client().oAuthApi.obtainToken({
clientId: this.config.oauthClientId,
clientSecret: this.config.oauthClientSecret,
grantType: "refresh_token",
refreshToken,
}));
});
}
pRetryOrThrow(fn) {
return __awaiter(this, void 0, void 0, function* () {
this.logger.verbose(this.pRetryOrThrow.name);
return pRetry(fn, {
onFailedAttempt: (error) => {
if (error instanceof ApiError) {
const isRetryable = error.statusCode >= HttpStatus.INTERNAL_SERVER_ERROR ||
error.statusCode === HttpStatus.TOO_MANY_REQUESTS;
if (!isRetryable || error.retriesLeft === 0) {
this.logger.error(this.pRetryOrThrow.name, error);
throw new InternalServerErrorException(error);
}
}
else {
throw error;
}
},
});
});
}
accumulateCatalogOrThrow(params) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
this.logger.verbose(this.accumulateCatalogOrThrow.name);
const { accessToken, types } = params;
const client = this.client({ accessToken });
const catalogObjects = [];
const theTypes = types.join(",");
let listCatalogResponse = yield this.pRetryOrThrow(() => client.catalogApi.listCatalog(undefined, theTypes));
catalogObjects.push(...((_a = listCatalogResponse === null || listCatalogResponse === void 0 ? void 0 : listCatalogResponse.result.objects) !== null && _a !== void 0 ? _a : []));
let cursor = listCatalogResponse === null || listCatalogResponse === void 0 ? void 0 : listCatalogResponse.result.cursor;
while (cursor !== undefined) {
listCatalogResponse = yield this.pRetryOrThrow(() => client.catalogApi.listCatalog(cursor, theTypes));
cursor = listCatalogResponse === null || listCatalogResponse === void 0 ? void 0 : listCatalogResponse.result.cursor;
catalogObjects.push(...((_b = listCatalogResponse === null || listCatalogResponse === void 0 ? void 0 : listCatalogResponse.result.objects) !== null && _b !== void 0 ? _b : []));
}
return catalogObjects;
});
}
uploadCatalogImageOrThrow(params) {
return __awaiter(this, void 0, void 0, function* () {
this.logger.verbose(this.uploadCatalogImageOrThrow.name);
const { idempotencyKey, objectId, file, caption, id } = params;
const bufferToStream = (buffer) => {
const stream = new Readable();
stream.push(buffer);
stream.push(null);
return stream;
};
const fileStream = bufferToStream(file.buffer);
const fileWrapper = new FileWrapper(fileStream, {
contentType: file.mimetype,
});
const response = yield this.pRetryOrThrow(() => this.client({
accessToken: params.accessToken,
}).catalogApi.createCatalogImage({
idempotencyKey: idempotencyKey,
objectId: objectId,
image: {
type: "IMAGE",
id: `#${id}`,
imageData: {
caption: caption,
},
},
}, fileWrapper));
return response.result;
});
}
};
NestSquareService = NestSquareService_1 = __decorate([
Injectable(),
__param(0, Inject(NEST_SQUARE_CONFIG_INJECTION_KEY)),
__metadata("design:paramtypes", [Object])
], NestSquareService);
export { NestSquareService };
//# sourceMappingURL=nest-square.service.js.map