2023-03-02 11:01:17 +00:00
|
|
|
import { EncryptedMetadataManager, MetadataEntry } from "@saleor/app-sdk/settings-manager";
|
2023-06-15 07:01:50 +00:00
|
|
|
import { Client, gql } from "urql";
|
2023-03-02 11:01:17 +00:00
|
|
|
import {
|
|
|
|
FetchAppDetailsDocument,
|
|
|
|
FetchAppDetailsQuery,
|
2023-04-17 11:58:21 +00:00
|
|
|
UpdateMetadataDocument,
|
2023-03-02 11:01:17 +00:00
|
|
|
} from "../../../generated/graphql";
|
|
|
|
|
2023-06-15 07:01:50 +00:00
|
|
|
gql`
|
|
|
|
mutation UpdateAppMetadata($id: ID!, $input: [MetadataInput!]!) {
|
|
|
|
updatePrivateMetadata(id: $id, input: $input) {
|
|
|
|
item {
|
|
|
|
privateMetadata {
|
|
|
|
key
|
|
|
|
value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
`;
|
|
|
|
|
|
|
|
gql`
|
|
|
|
query FetchAppDetails {
|
|
|
|
app {
|
|
|
|
id
|
|
|
|
privateMetadata {
|
|
|
|
key
|
|
|
|
value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
`;
|
2023-03-30 11:12:52 +00:00
|
|
|
|
2023-06-15 07:01:50 +00:00
|
|
|
export async function fetchAllMetadata(client: Client): Promise<MetadataEntry[]> {
|
2023-03-02 11:01:17 +00:00
|
|
|
const { error, data } = await client
|
|
|
|
.query<FetchAppDetailsQuery>(FetchAppDetailsDocument, {})
|
|
|
|
.toPromise();
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
return data?.app?.privateMetadata.map((md) => ({ key: md.key, value: md.value })) || [];
|
|
|
|
}
|
|
|
|
|
2023-06-15 07:01:50 +00:00
|
|
|
export async function mutateMetadata(client: Client, metadata: MetadataEntry[], appId: string) {
|
2023-03-02 11:01:17 +00:00
|
|
|
const { error: mutationError, data: mutationData } = await client
|
2023-04-17 11:58:21 +00:00
|
|
|
.mutation(UpdateMetadataDocument, {
|
2023-03-02 11:01:17 +00:00
|
|
|
id: appId,
|
|
|
|
input: metadata,
|
|
|
|
})
|
|
|
|
.toPromise();
|
|
|
|
|
|
|
|
if (mutationError) {
|
|
|
|
throw new Error(`Mutation error: ${mutationError.message}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
mutationData?.updatePrivateMetadata?.item?.privateMetadata.map((md) => ({
|
|
|
|
key: md.key,
|
|
|
|
value: md.value,
|
|
|
|
})) || []
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-06-15 07:01:50 +00:00
|
|
|
export const createSettingsManager = (client: Client, appId: string) => {
|
|
|
|
/*
|
2023-04-17 11:58:21 +00:00
|
|
|
* EncryptedMetadataManager gives you interface to manipulate metadata and cache values in memory.
|
|
|
|
* We recommend it for production, because all values are encrypted.
|
|
|
|
* If your use case require plain text values, you can use MetadataManager.
|
|
|
|
*/
|
2023-03-02 11:01:17 +00:00
|
|
|
return new EncryptedMetadataManager({
|
|
|
|
// Secret key should be randomly created for production and set as environment variable
|
|
|
|
encryptionKey: process.env.SECRET_KEY!,
|
|
|
|
fetchMetadata: () => fetchAllMetadata(client),
|
2023-06-15 07:01:50 +00:00
|
|
|
mutateMetadata: (metadata) => mutateMetadata(client, metadata, appId),
|
2023-03-02 11:01:17 +00:00
|
|
|
});
|
|
|
|
};
|