Skip to content

Instantly share code, notes, and snippets.

@woss
Created July 1, 2022 10:31
Show Gist options
  • Save woss/d22a486c052fcb623110632dd890d83f to your computer and use it in GitHub Desktop.
Save woss/d22a486c052fcb623110632dd890d83f to your computer and use it in GitHub Desktop.
import axios from 'axios';
import { fromBuffer } from 'file-type';
import { equals, includes, isEmpty, isNil, last, split } from 'ramda';
/**
* Checks is the payload image and if it is will also check do we need to process it, the searchParams are not empty. Internally this method will fetch the minimum amount of bytes (4100) using the Range header and try to determine the mime type.
*
* Example:
*
* ```ts
* // this will return false because it doesn't have the searchParams
* url = 'ipfs/bafykCID/image1.png'
*
* // this will return true because it has the searchParams
* url = 'ipfs/bafykCID/image1.png?w=100'
* ```
* @param url -
* @param queryParams -
* @returns
*/
export async function imageTypeBasedOnIpfsCid(
url: URL,
queryParams: Record<string, unknown>
): Promise<{ process: boolean; cid: string }> {
// @TODO maybe use .head and diff response type
const c = await axios.get(url.toString(), {
responseType: 'arraybuffer',
// get first minimum amount of bytes to see is it image or not
headers: { Range: `bytes=0-${minimumBytes}` }
});
const mimeT = await fromBuffer(c.data);
const res = {
mime: mimeT.mime,
cid: last(split(',', c.headers['x-ipfs-roots'])) as string
};
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment