So after a week of rigorous battle with the code and the API , i finally figured out how to save the discount as a metafield.
I also encountered a lot of errors including 405, 500, 501
I’m sharing the solution here, so that it will helpful for anyone Or some Expert can suggest a better way to do the same.
Client side
const options={headers:{"Content-Type":"application/json"}};
axios.post("/metafield",
{metafield:{namespace:"shop",key:"discount",value:this.state.discount,value_type:"string"}},options)
.then(o=>{console.log(o)},o=>{console.log(o)});
Server side
router.post("/metafield", koaBody(), async (ctx) => {
try {
const data = JSON.stringify(ctx.request.body);
const apikey = ctx.cookies.get("accessToken");
const shop = "xxxxxxxxxxxx.myshopify.com";
const response = await fetch(
`https://${shop}/admin/api/2020-04/metafields.json`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": apikey,
},
body: data,
}
);
const responseJson = await response.json();
ctx.body = responseJson;
} catch (error) {
console.log(error);
}
});