2022-09-21 09:25:01 +00:00
|
|
|
import type { Handler } from "retes";
|
|
|
|
import { toNextHandler } from "retes/adapter";
|
|
|
|
import { withMethod } from "retes/middleware";
|
|
|
|
import { Response } from "retes/response";
|
|
|
|
|
|
|
|
import { SALEOR_DOMAIN_HEADER } from "../../const";
|
|
|
|
import { withAuthTokenRequired, withSaleorDomainPresent } from "../../middleware";
|
2022-10-11 07:40:08 +00:00
|
|
|
import { HasAPL } from "../../saleor-app";
|
2022-09-21 09:25:01 +00:00
|
|
|
|
2022-10-11 07:40:08 +00:00
|
|
|
export type CreateAppRegisterHandlerOptions = HasAPL;
|
2022-09-21 09:25:01 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates API handler for Next.js. Creates handler called by Saleor that registers app.
|
|
|
|
* Hides implementation details if possible
|
|
|
|
* In the future this will be extracted to separate sdk/next package
|
|
|
|
*/
|
|
|
|
export const createAppRegisterHandler = ({ apl }: CreateAppRegisterHandlerOptions) => {
|
|
|
|
const baseHandler: Handler = async (request) => {
|
|
|
|
const authToken = request.params.auth_token;
|
|
|
|
const saleorDomain = request.headers[SALEOR_DOMAIN_HEADER] as string;
|
|
|
|
|
2022-10-11 07:40:08 +00:00
|
|
|
const { ready: aplReady } = await apl.isReady();
|
|
|
|
|
|
|
|
if (!aplReady) {
|
|
|
|
return new Response(
|
|
|
|
{
|
|
|
|
success: false,
|
|
|
|
error: {
|
|
|
|
code: "APL_NOT_READY",
|
|
|
|
message: "App is not ready yet",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
status: 503,
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-09-21 09:25:01 +00:00
|
|
|
try {
|
|
|
|
await apl.set({ domain: saleorDomain, token: authToken });
|
|
|
|
} catch {
|
|
|
|
return Response.InternalServerError({
|
|
|
|
success: false,
|
|
|
|
error: {
|
|
|
|
message: "Registration failed: could not save the auth data.",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return Response.OK({ success: true });
|
|
|
|
};
|
|
|
|
|
|
|
|
return toNextHandler([
|
|
|
|
withMethod("POST"),
|
|
|
|
withSaleorDomainPresent,
|
|
|
|
withAuthTokenRequired,
|
|
|
|
baseHandler,
|
|
|
|
]);
|
|
|
|
};
|