saleor-apps-redis_apl/apps/invoices/src/pages/api/register.ts
Lukasz Ostrowski 830cfe92ce
Extract logger (#439)
* Extract logger

* Replace logger with shared one

* Replace CRM logger with shared one

* Replace E&M logger with shared one

* Replace invoices logger with shared one

* Replace Products Feed logger with shared one

* Replace Search logger with shared one

* Replace Taxes logger with shared one

* Uninstall pino from apps direct dependency

* Update docs

* Update changeset

* Bumped Klaviyo typescript version to hopefully unblock the build

* Change packageManager field to pnpm 8.2.0

* removed package manager field from klaviyo package.json
2023-05-05 08:15:47 +02:00

88 lines
2.5 KiB
TypeScript

import { createAppRegisterHandler } from "@saleor/app-sdk/handlers/next";
import { REQUIRED_SALEOR_VERSION, saleorApp } from "../../saleor-app";
import { gql } from "urql";
import { createClient } from "../../lib/graphql";
import { SaleorVersionQuery } from "../../../generated/graphql";
import { createLogger } from "@saleor/apps-shared";
import { SaleorVersionCompatibilityValidator } from "../../lib/saleor-version-compatibility-validator";
const allowedUrlsPattern = process.env.ALLOWED_DOMAIN_PATTERN;
const SaleorVersion = gql`
query SaleorVersion {
shop {
version
}
}
`;
/**
* Required endpoint, called by Saleor to install app.
* It will exchange tokens with app, so saleorApp.apl will contain token
*/
export default createAppRegisterHandler({
apl: saleorApp.apl,
/**
* Prohibit installation from Saleors other than specified by the regex.
* Regex source is ENV so if ENV is not set, all installations will be allowed.
*/
allowedSaleorUrls: [
(url) => {
if (allowedUrlsPattern) {
const regex = new RegExp(allowedUrlsPattern);
return regex.test(url);
}
return true;
},
],
/**
* Check Saleor version and reject installation if it doesn't match
*
* TODO: Consider moving to app-sdk and do it under the hood
*
* Also, consume version, if possible, from the request directly
* @see https://github.com/saleor/saleor/issues/12144
*/
async onRequestVerified(req, { authData: { token, saleorApiUrl }, respondWithError }) {
const logger = createLogger({
context: "onRequestVerified",
});
try {
const client = createClient(saleorApiUrl, async () => {
return {
token,
};
});
const saleorVersion = await client
.query<SaleorVersionQuery>(SaleorVersion, {})
.toPromise()
.then((res) => {
return res.data?.shop.version;
});
logger.debug({ saleorVersion }, "Received saleor version from Shop query");
if (!saleorVersion) {
throw new Error("Saleor Version couldnt be fetched from the API");
}
new SaleorVersionCompatibilityValidator(REQUIRED_SALEOR_VERSION).validateOrThrow(
saleorVersion
);
} catch (e: unknown) {
const message = (e as Error)?.message ?? "Unknown error";
logger.debug({ message }, "Failed validating semver, will respond with error and status 400");
throw respondWithError({
message: message,
status: 400,
});
}
},
});