autumn-js
Version:
Autumn JS Library
116 lines (112 loc) • 2.63 kB
JavaScript
import {
toBackendError,
toBackendRes
} from "./chunk-UJN5NVTZ.mjs";
import {
logger
} from "./chunk-SGEUXFOF.mjs";
// src/utils/toSnakeCase.ts
function stringToSnakeCase(str) {
return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
}
var toSnakeCase = ({
obj,
excludeKeys,
excludeChildrenOf
}) => {
if (Array.isArray(obj)) {
return obj.map(
(item) => toSnakeCase({ obj: item, excludeKeys, excludeChildrenOf })
);
} else if (obj !== null && typeof obj === "object") {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => {
const snakeKey = stringToSnakeCase(key);
if (excludeKeys?.includes(key)) {
return [key, value];
}
if (excludeChildrenOf?.includes(key)) {
return [snakeKey, value];
}
return [
snakeKey,
toSnakeCase({
obj: value,
excludeKeys,
excludeChildrenOf
})
];
})
);
}
return obj;
};
// src/libraries/backend/utils/withAuth.ts
var withAuth = ({
fn,
requireCustomer = true,
suppressLogs = false
}) => {
return async ({
autumn,
body,
path,
getCustomer,
pathParams,
searchParams
}) => {
let authResult = await getCustomer();
let customerId = authResult?.customerId;
if (!customerId && requireCustomer) {
if (body?.errorOnNotFound === false) {
return {
statusCode: 202,
body: null
};
} else {
if (!suppressLogs) {
logger.error(
`[Autumn]: customerId returned from identify function is ${customerId}`
);
}
return toBackendError({
path,
message: `customerId returned from identify function is ${customerId}`,
code: "no_customer_id",
statusCode: 401
});
}
}
let cusData = authResult?.customerData || body?.customer_data;
if (body) {
body = toSnakeCase({
obj: body,
excludeChildrenOf: ["checkoutSessionParams", "properties"]
});
}
try {
let res = await fn({
body,
autumn,
customer_id: customerId,
customer_data: cusData,
pathParams,
searchParams
});
return toBackendRes({ res });
} catch (error) {
if (!suppressLogs) {
logger.error(`${error.message}`);
}
return toBackendError({
path,
message: error.message || "unknown error",
code: "internal_error"
});
}
};
};
export {
toSnakeCase,
withAuth
};