Of course, this i my codes:
import {
getCustomerMetafield,
getProductMetafield,
getShopifyClientByShop,
upsertMetafields,
} from "@/lib/shopify";
import { NextRequest, NextResponse } from "next/server";
export async function GET() {}
export async function POST(req: NextRequest) {
const { value, customerId, productId, shop } = (await req.json()) as {
customerId: number;
productId: string;
value: boolean;
shop: string;
};
const shopifyClient = await getShopifyClientByShop(shop);
if (!shopifyClient) return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
try {
const [products, customers] = await Promise.all([
getCustomerMetafield(
shopifyClient.client,
`gid://shopify/Customer/${customerId}`,
"wishlist",
"customer"
),
getProductMetafield(
shopifyClient.client,
`gid://shopify/Product/${productId}`,
"wishlisted_customers",
"product"
),
]);
let wishlistedProducts: string[] = [];
let wishlistedCustomers: string[] = [];
if (products.metafield?.value) {
wishlistedProducts = JSON.parse(products.metafield.value);
}
if (customers.metafield?.value) {
wishlistedCustomers = JSON.parse(customers.metafield.value);
}
if (value) {
wishlistedProducts.push(productId);
wishlistedCustomers.push(String(customerId));
} else {
wishlistedProducts = wishlistedProducts.filter((id) => id !== productId);
wishlistedCustomers = wishlistedCustomers.filter((id) => id !== String(customerId));
}
await upsertMetafields(shopifyClient.client, [
{
namespace: "customer",
key: "wishlist",
type: "list.single_line_text_field",
value: JSON.stringify(wishlistedProducts),
ownerId: `gid://shopify/Customer/${customerId}`,
},
{
namespace: "product",
key: "wishlisted_customers",
type: "list.single_line_text_field",
value: JSON.stringify(wishlistedCustomers),
ownerId: `gid://shopify/Product/${productId}`,
},
]);
return NextResponse.json({ message: "success" });
} catch (err) {
return NextResponse.json({ message: "Failed to update your wishlist" }, { status: 500 });
}
}
export const getCustomerMetafield = async (
client: Shopify,
ownerId: string,
key: string,
namespace: string = PROFILE_NAMESPACE
) => {
try {
const query = `query {
customer(id: "${ownerId}") {
metafield(namespace: "${namespace}", key: "${key}") {
id
value
}
}
}`;
const data: {
customer: {
metafield: {
value: string;
} | null;
};
} = await client.graphql(query);
return data.customer;
} catch (err: any) {
throw new Error(err);
}
};