How can I dynamically query discountNode metafield in my app?

How can I dynamically query discountNode metafield in my app?

jacobovelasquez
Shopify Partner
6 0 0

Hi Guys I am doing an app with remix for discounts, all is going good and I am coding a DataTable where the merchant can edit the discount, when the discount is clicked it takes the merchant to the specific page successfully, but I dont know how to query the metafields for that specific discount dynamically so it works everywhere.

Here is what i have so far in my query:

export async function loader({ request }) {
const { admin } = await shopify.authenticate.admin(request);
const discountCodeId = `gid://shopify/DiscountAutomaticNode/1095825490072`;
const response = await admin.graphql(`
{
discountNode(id: "${discountCodeId}") {
id
metafield(namespace: "volume-discount", key:"function-configuration"){
value
}
discount {
... on DiscountCodeBasic {
title
}
... on DiscountCodeBxgy {
title
}
... on DiscountCodeFreeShipping {
title
}
... on DiscountAutomaticApp {
title
}
... on DiscountAutomaticBasic {
title
}
... on DiscountAutomaticBxgy {
title
}
... on DiscountAutomaticFreeShipping {
title
}
}
}
}
`);
 
const parsedResponse = await response.json();
 
return json({
discount: parsedResponse.data,
});
}

and this is how I create the it:
export const action = async ({ params, request }) => {
const { functionId } = params;
const { admin } = await shopify.authenticate.admin(request);
const formData = await request?.formData();
const {
title,
method,
code,
combinesWith,
usageLimit,
appliesOncePerCustomer,
startsAt,
endsAt,
configuration,
} = JSON.parse(formData.get("discount"));

const baseDiscount = {
functionId,
title,
combinesWith,
startsAt: new Date(startsAt),
endsAt: endsAt && new Date(endsAt),
};

if (method === DiscountMethod.Code) {
const baseCodeDiscount = {
...baseDiscount,
title: code,
code,
usageLimit,
appliesOncePerCustomer,
};

const response = await admin.graphql(
`#graphql
mutation CreateCodeDiscount($discount: DiscountCodeAppInput!) {
discountCreate: discountCodeAppCreate(codeAppDiscount: $discount) {
userErrors {
code
message
field
}
}
}`,
{
variables: {
discount: {
...baseCodeDiscount,
metafields: [
{
namespace: "$app:volume-discount",
key: "function-configuration",
type: "json",
value: JSON.stringify({
quantity: configuration.quantity,
percentage: configuration.percentage,
bundles: configuration.bundles
}),
},
],
},
},
}
);

const responseJson = await response.json();
const errors = responseJson.data.discountCreate?.userErrors;
return json({ errors });
} else {
const response = await admin.graphql(
`#graphql
mutation CreateAutomaticDiscount($discount: DiscountAutomaticAppInput!) {
discountCreate: discountAutomaticAppCreate(automaticAppDiscount: $discount) {
userErrors {
code
message
field
}
}
}`,
{
variables: {
discount: {
...baseDiscount,
metafields: [
{
namespace: "$app:volume-discount",
key: "function-configuration",
type: "json",
value: JSON.stringify({
quantity: configuration.quantity,
percentage: configuration.percentage,
bundles: configuration.bundles
}),
},
],
},
},
}
);

const responseJson = await response.json();
const errors = responseJson.data.discountCreate?.userErrors;
return json({ errors });
}
};


Reply 1 (1)

Hirano_00
Shopify Partner
76 10 13

Hi @jacobovelasquez,

 

I have created a sample code.

If there is anything here that’s unclear please do let me know!

 

app/routes/app.discount.$functionId.$id.tsx

export const loader = async ({ params, request }: LoaderFunctionArgs) => {
  const { admin } = await shopify.authenticate.admin(request);
  const { id } = params;
  const discountNode = await getDiscount(admin, id!);
  return json({ discountNode });
};

const getDiscount = async (
  admin: AdminApiContext<RestResources>,
  id: string,
) => {
  const response = await admin.graphql(
    getDiscountNode(),
    {
      variables: {
        id: 'gid://shopify/DiscountNode/' + id,
        namespace: METAFIELD_NAMESPACE,
        key: METAFIELD_CONFIGURATION_KEY
      },
    }
  );
  const responseJson = await response.json();
  const discountNode = responseJson.data.discountNode;
  if (!discountNode) return undefined;
  if (!discountNode.metafield) return undefined;

  if (typeof discountNode.metafield.value !== 'object') {
    const value = JSON.parse(discountNode.metafield.value)
    value.volume = value.volume.map((obj: any) => ({
      quantity: String(obj.quantity),
      percentage: String(obj.percentage)
    }));
    discountNode.metafield.value = value;
  }

  return discountNode;
}

const getDiscountNode = () => {
  return `#graphql
    query getDiscountNode($id: ID!, $namespace: String!, $key: String!){
      discountNode(id: $id) {
        discount {
          ... on DiscountAutomaticApp {
            __typename
            asyncUsageCount
            combinesWith {
              orderDiscounts
              productDiscounts
              shippingDiscounts
            }
            endsAt
            startsAt
            status
            title
          }
          ... on DiscountCodeApp {
            __typename
            asyncUsageCount
            appliesOncePerCustomer
            codeCount
            combinesWith {
              orderDiscounts
              productDiscounts
              shippingDiscounts
            }
            endsAt
            startsAt
            status
            title
            usageLimit
            codes(first: 1) {
              edges {
                node {
                  code
                }
              }
            }
          }
        }
        id
        metafield(namespace: $namespace, key: $key) {
          value
          id
        }
      }
    }`
}