bananas-commerce
Version:
A client for bananas-commerce with support for TypeScript
80 lines (79 loc) • 3.21 kB
JavaScript
import { casedObjectKeys, } from "../util/casedObjectKeys.js";
import { formatVariableResult, } from "../util/formatVariableResult.js";
import { Extension } from "../extension.js";
export class Ingrid extends Extension {
constructor() {
super(...arguments);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: "ingrid"
});
}
/**
* Initializes or updates an Ingrid-session, where the HTML-snippet for the Ingrid widget (`shipping_data`)
* and a shipping reference `shipping.reference` is included in the response. The shipping reference
* is used to initialize a purchase. If a shipping reference is specified in the arguments, a different
* shipping reference may be returned.
*/
async begin(args) {
this.assertLoaded();
const { siteCode = this.defaults.siteCode, countryCode = this.defaults.countryCode, ...body } = args;
if (!siteCode) {
return {
_type: "internal-error",
detail: "A site code must be specified either in the constructor of BananasCommerce " +
"or in the arguments passed to BananasCommerce.ingrid.begin.",
};
}
if (!countryCode) {
return {
_type: "internal-error",
detail: "A country code must be specified either in the constructor of BananasCommerce " +
"or in the arguments passed to BananasCommerce.ingrid.begin.",
};
}
const response = await this.catchApiError(this.fetcher.endpoint("/api/v1/{site_code}/ingrid/begin/").method("post")({
body: {
...casedObjectKeys(body, "snake"),
country_code: countryCode,
},
path: { site_code: siteCode },
}));
return formatVariableResult({ ...response, data: casedObjectKeys(response.data, "camel") }, (response) => {
switch (response.status) {
case 200:
return "created";
case 201:
return "updated";
case 400:
return "invalid-args";
case 404:
return "not-found";
case 503:
return "internal-error";
}
});
}
/**
* Confirms the delivery of an Ingrid-session. It must be called before sealing a purchase
* with the same shipping reference.
*/
async confirm(args) {
this.assertLoaded();
const response = await this.catchApiError(this.fetcher.endpoint("/api/v1/ingrid/confirm/").method("post")({
body: casedObjectKeys(args, "snake"),
}));
return formatVariableResult({ ...response, data: casedObjectKeys(response.data, "camel") }, (response) => {
switch (response.status) {
case 204:
return "success";
case 400:
return "invalid-args";
case 503:
return "internal-error";
}
});
}
}