Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 34 additions & 10 deletions src/api/platforms/payment-instruments.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
import { determineError } from '../../services/errors.js';
import { get, patch, post } from '../../services/http.js';
import { buildQueryParams, encodePathSegment } from '../../services/utils.js';
import { buildQueryParams, encodePathSegment, setHeader } from '../../services/utils.js';

// Path segments appended to the API base (config.host).
const ACCOUNTS_PATH = 'accounts';
const ENTITIES_PATH = 'entities';
const INSTRUMENTS_PATH = 'instruments';
const PAYMENT_INSTRUMENTS_PATH = 'payment-instruments';

// Whether a request body still carries an if-match key in body.headers, the form earlier versions
// read the ETag from; it is only detected, to warn, never sent as a header.
const hasIfMatchInBodyHeaders = (body) =>
body !== null &&
typeof body === 'object' &&
body.headers !== null &&
typeof body.headers === 'object' &&
Object.keys(body.headers).some((name) => name.trim().toLowerCase() === 'if-match');

/**
* Payment instruments for sub-entities (payouts).
*
Expand Down Expand Up @@ -48,27 +57,42 @@
*
* The API reads the ETag only from the If-Match HTTP header: without it the update fails with
* 428 Precondition Required, and with a stale one with 412 Precondition Failed. Pass the ETag
* from the ETag header of the GET in body.headers['if-match']; every key of body.headers is
* sent as an HTTP header.
* - body.label: [Optional] string, 1 to 50 characters.
* - body.default: [Optional] boolean. Deprecated by the API: for scheduled payouts the first
* payment instrument created for a currency is used; to change it, update the payout
* schedule.
* - body.headers: { 'if-match': etag }, [Required] by the API.
* from the ETag header of the GET in ifMatch. The body is sent as it is, as JSON; none of its
* keys is sent as an HTTP header.
* - body.label: string. A reference that you can use to identify the payment instrument.
* [Optional] max 50 characters, min 1 characters.
* - body.default: boolean. Whether the payment instrument should be set as the default payout
* destination. [Optional] Deprecated by the API: for ad-hoc payouts the payment instrument is
* given in the payout request; for scheduled payouts the first payment instrument created for
* a currency is used; to change it, update the payout schedule.
*
* @param {string} entityId Sub-entity id.
* @param {string} id Payment instrument's id.
* @param {Object} body The update, as described above.
* @param {string} ifMatch The ETag of the payment instrument (e.g. Y3Y9MCZydj0w), sent as the
* If-Match header; [Required] by the API: without it (undefined or null) no If-Match header is
* sent, the API answers 428, and a warning is emitted when body.headers holds an if-match.
* @return {Promise<Object>} A promise to the Platforms response: the instrument id and _links.
* @throws {ValueError} If entityId or id is undefined, null, empty, "." or "..", or contains
* "/", "\", an ASCII control character or an unpaired surrogate.
*/
async updatePaymentInstrumentDetails(entityId, id, body) {
async updatePaymentInstrumentDetails(entityId, id, body, ifMatch) {
try {
const ifMatchGiven = ifMatch !== undefined && ifMatch !== null;
if (!ifMatchGiven && hasIfMatchInBodyHeaders(body)) {
process.emitWarning(
'updatePaymentInstrumentDetails: body.headers is sent only inside the request body, ' +
'not as HTTP headers. Pass the ETag in the ifMatch parameter to send the If-Match header.'
);
}
const config = ifMatchGiven
? { ...this.config, headers: setHeader({ ...(this.config.headers || {}) }, 'If-Match', ifMatch) }

Check warning on line 89 in src/api/platforms/payment-instruments.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

The empty object is useless.

See more on https://sonarcloud.io/project/issues?id=checkout_checkout-sdk-node&issues=AaJBcmRNIeA8zVU2Gt2X&open=AaJBcmRNIeA8zVU2Gt2X&pullRequest=489
: this.config;

const response = await patch(
this.config.httpClient,
`${this.config.host}/${ACCOUNTS_PATH}/${ENTITIES_PATH}/${encodePathSegment(entityId, 'entityId')}/${PAYMENT_INSTRUMENTS_PATH}/${encodePathSegment(id, 'id')}`,
this.config,
config,
this.config.sk,
body
);
Expand Down
5 changes: 3 additions & 2 deletions src/api/platforms/platforms.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ export default class Platforms {
return this.paymentInstruments.getPaymentInstrumentDetails(entityId, id);
}

async updatePaymentInstrumentDetails(entityId, id, body) {
return this.paymentInstruments.updatePaymentInstrumentDetails(entityId, id, body);
/** Update a payment instrument's details, with its ETag in ifMatch. See PaymentInstruments.updatePaymentInstrumentDetails. */
async updatePaymentInstrumentDetails(entityId, id, body, ifMatch) {
return this.paymentInstruments.updatePaymentInstrumentDetails(entityId, id, body, ifMatch);
}

async createPaymentInstrument(id, body) {
Expand Down
52 changes: 43 additions & 9 deletions src/services/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
SANDBOX_ACCESS_URL,
} from '../config.js';
import Environment from '../Environment.js';
import { setHeader } from './utils.js';
import { ApiError, ApiTimeout, AuthenticationError, determineError } from './errors.js';

import pjson from '../../package.json' with { type: 'json' };
Expand Down Expand Up @@ -55,27 +56,60 @@ function buildJsonResponse(response) {
});
}

// axios reads `common` and per-method keys of the request headers as header groups and merges
// them with the headers (axios lib/core/Axios.js, lib/core/methodList.js).
export const AXIOS_HEADER_GROUPS = ['common', 'get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'purge', 'link', 'unlink', 'query'];

// Replaces every object under a header group key (in any case, as axios merges the keys) with a
// plain copy without the given names (compared as axios compares them), read once, so no group
// can change the headers the SDK sets, whatever kind of object it is.
const withoutNamesInGroups = (headers, names) => {
Object.keys(headers)
.filter((key) => AXIOS_HEADER_GROUPS.includes(key.toLowerCase()))
.filter((key) => headers[key] !== null && typeof headers[key] === 'object')
.forEach((key) => {
headers[key] = Object.fromEntries(
Object.entries(headers[key]).filter(([name]) => !names.includes(name.trim().toLowerCase()))
);
});
return headers;
};

/**
* Headers of an API request: the configured headers (options.headers and the ones SDK methods
* add from their parameters) and the SDK's own. The request body is never read for headers: a
* body is only ever sent as the body.
*
* @param {Object} config SDK configuration.
* @param {Object} [request] Request body; only the multipart form the SDK builds for file uploads
* (config.formData) adds its content type.
* @param {string} authHeader Authorization value.
* @param {string} [idempotencyKey] Cko-Idempotency-Key value.
* @return {Object} The headers. Authorization, Content-Type (multipart and text/csv included) and
* Cko-Idempotency-Key, when the SDK sets them, are the SDK's values whatever the configured
* headers hold; a configured Cko-Idempotency-Key is kept when no idempotency key is passed.
*/
function getRequestHeaders(config, request, authHeader, idempotencyKey) {
let headers = {
const headers = {
...config.headers,
Authorization: authHeader,
'Cache-Control': 'no-cache',
pragma: 'no-cache',
'user-agent': `checkout-sdk-node/${pjson.version}`,
};

if (request && request.headers) {
headers = { ...headers, ...request.headers };
}
withoutNamesInGroups(
headers,
idempotencyKey === undefined ? ['authorization', 'content-type'] : ['authorization', 'content-type', 'cko-idempotency-key']
);
setHeader(headers, 'Authorization', authHeader);

if (!config.formData) {
headers['Content-Type'] = config.csv ? 'text/csv' : 'application/json';
setHeader(headers, 'Content-Type', config.csv ? 'text/csv' : 'application/json');
} else if (request && typeof request.getHeaders === 'function') {
headers = { ...headers, ...request.getHeaders() };
Object.entries(request.getHeaders()).forEach(([name, value]) => setHeader(headers, name, value));
}

if (idempotencyKey !== undefined) {
headers['Cko-Idempotency-Key'] = idempotencyKey;
setHeader(headers, 'Cko-Idempotency-Key', idempotencyKey);
}

return headers;
Expand Down
18 changes: 18 additions & 0 deletions src/services/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,21 @@ export const encodePathSegment = (value, name) => {

return encodeURIComponent(segment);
};

/**
* Set a header so that it is the only one of its name: another configured header with the same
* name, as HTTP clients compare names, is removed first.
*
* @param {Object} headers Plain object of headers, changed in place.
* @param {string} name The header name, in the case to send.
* @param {*} value The header value.
* @return {Object} The same headers object.
*/
export const setHeader = (headers, name, value) => {
const lowerName = name.toLowerCase();
Object.keys(headers)
.filter((key) => key.trim().toLowerCase() === lowerName)
.forEach((key) => delete headers[key]);
headers[name] = value;
return headers;
};
Loading