Hello… Shopify… development…
I’m kinda hacking my way through developing custom shopify apps, i have met satan a few times throughout my 2-3 weeks of development (no native cart add/remove events for one, which ultimately would be a 20 minutes addon for any experienced developer… a simple custom js event, so that you don’t have to query any API to get changes.).
How do I access app-owned metafields in Shopify .liquidated files?
This is how I hoped I could do it:
shop.metafields['$app:discount-shipping']['function-configuration']
This is how I set/read the metafields in my admin .tsx file:
export const loader: LoaderFunction = async ({request}) => {
const {admin} = await authenticate.admin(request);
const metaFields = await getShopMetafields(admin, "$app:discount-shipping", 10);
let settings = {};
if (metaFields && metaFields[0]) {
settings = metaFields[0];
}
return {
settings: settings,
}
};
export async function action({request}: {request: Request}) {
const formData = await request.formData();
const {admin} = await authenticate.admin(request);
const shop = await getShop(admin);
const responseMetafieldSet = await setMetaField(
admin,
"$app:discount-shipping",
"function-configuration",
"json",
JSON.stringify({
targetSetting: formData.get("targetSetting"),
discountValue: Number(formData.get("discountValue")),
discountType: formData.get("discountType"),
textAlignment: formData.get("textAlignment"),
completedBackground: formData.get("completedBackground"),
missingBackground: formData.get("missingBackground"),
}),
shop.id
);
const errors = responseMetafieldSet?.userErrors;
if (errors && errors.length > 0) {
return json({ success: false, errors: errors});
}
return json({ success: true});
}
And the helper function:
export async function getShopMetafields(
admin: AdminApiContext<RestResources>,
namespace: string,
first: number = 10
) {
return await admin.graphql(`#graphql
query {
shop {
metafields(namespace: "${namespace}", first: ${first}) {
edges {
node {
id
namespace
key
value
type
}
}
}
}
}`
).then((e: any) => e.json())
.then((e: any) => e.data.shop.metafields.edges.map((edge: any) => edge.node));
}
How do I access the app owned meta field? right now I am doing this, which works if I ofcourse change the namespace in my read/write functions above:
{% assign free_shipping_settings_json = shop.metafields.checkout_champ_free_shipping.settings | parse_json %}
Also, “| parse_json” works… but gives CLI errors “| json” does not work.
Random Rant:
Why have shopify even created a .liquid template engine, basically we are using JSX/TSX to develop components in the admin panel, why not use the same instead of .liquid files, then we could reuse components? to me this whole .liquid templating seems utterly bleep, I have to build stuff twice… once for a visual representation in the admin panel, and a completely other one in the .liquid files.