Skip to content

Instantly share code, notes, and snippets.

@JohnRSim
Created June 28, 2023 14:35
Show Gist options
  • Save JohnRSim/c428692453c504a0b66a55d0dcfbe3d8 to your computer and use it in GitHub Desktop.
Save JohnRSim/c428692453c504a0b66a55d0dcfbe3d8 to your computer and use it in GitHub Desktop.
Quick Example of returning asset data of an image parsing it to generate and inject picture tag
// Globals || ENV
const OCMURL = 'https://<instaance>-<cloud>.ocecdn.oraclecloud.com';
const APIVer = 'v1.1';
const channelToken = '9d4b5f18232740db944841a0e828a83b';
/**
* Custom err class for fetch
*/
class ResponseError extends Error {
constructor(message, response) {
super(message);
this.response = response;
}
response;
}
/**
* inject img
*/
async function injectImage(id, target, alt) {
try {
//fetch asset info
const ocmURL = `${OCMURL}/content/published/api/${APIVer}/items/${id}?channelToken=${channelToken}`;
const assetRes = await fetch(ocmURL);
//check response
if (!assetRes.ok) {
throw new ResponseError('Bad response', assetRes);
}
//parse response data
const imgData = await assetRes.json();
const asset = getSourceSet(imgData);
//gen picture tag
const img = `
<picture>
<source
type="image/webp"
srcset="${asset.srcset}"
sizes="(min-width: 480px) 200px, 150px" />
<source
srcset="${asset.jpgSrcset}"
sizes="(min-width: 480px) 200px, 150px" />
<img
src="${asset.small}"
loading="lazy"
alt="${alt}
width="${asset.width}"
height="${asset.height}" />
</picture>
`;
//childImg.src = getSourceSet(data);
//setHTML experimental not supported in FF
//block.setHTML(img, { sanitizer: sanitizer1 });
//use innerHTML
target.innerHTML = img;
} catch (err) {
if (err instanceof ResponseError) {
console.error(err.response?.status);
switch(err.response?.status) {
/* Handle based on status */
case 400: /* Handle */ break
case 401: /* Handle */ break
case 404: /* Handle */ break
case 500: /* Handle */ break
}
}
throw new Error('Request failed', {
cause: err,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment