Say hi to our new asset utilities library!
The new library of asset utilities makes it even more convenient to build with images and files from Sanity.io
Sanity.io comes with a capable asset pipeline CDN. Upload a large resolution image, and request the size, crop, format, and quality you need. It will be delivered from the edge network, ensuring performance and efficiency for your application. Now we have published a library with a bunch of utility functions that is useful when building with assets from Sanity.
It‘s perhaps not breaking news as far as product releases go. But we think the asset-utils provides some developer experience convenience and wanted to let you know about it. It’s also an example of our continued work to provide those who work with TypeScript, with the types and interfaces they need in their projects.
You add the asset utilities to your project using npm or yarn:
npm i @sanity/asset-utils # or yarn add @sanity/asset-utils
Since we wrote asset-utils in TypeScript with TSDoc-annotations, we could generate some comprehensive reference documentation for it as well. You can explore it on GitHub, and it should appear as helpful tool-tips and auto-complete suggestions if you are using VS Code and other capable code editors.
With the asset-utils library, you will be able to generate file URLs from its asset id and the project configuration that you have in your project. It‘s focused around taking the least information possible, and make the most useful thing out of it:
Build a file object from the asset id
import { getFile } from "@sanity/asset-utils";
import { client } from "./client";
const doc = {
_createdAt: "2019-03-07T08:07:57Z",
_id: "mFXWUiXzYAP1MwiPjbWVJu",
_rev: "CbupMhrv0BU2npu4xq78VL",
_type: "podcast",
_updatedAt: "2019-08-23T07:40:10Z",
description: "The story behind GROQ",
fileAsset: {
_type: "file",
asset: {
_ref: "file-d19e06dcf4aff5a3eafd9d7b58c8703ea6e6b433-m4a",
_type: "reference"
}
},
title: "How GROQ became GROQ"
};
const file = getFile(doc.fileAsset, client.config());
console.log(file)
Outputs a file object with useful information
{
"asset": {
"_id": "file-d19e06dcf4aff5a3eafd9d7b58c8703ea6e6b433-m4a",
"_type": "sanity.fileAsset",
"assetId": "d19e06dcf4aff5a3eafd9d7b58c8703ea6e6b433",
"extension": "m4a",
"metadata": {},
"url": "https://cdn.sanity.io/files/zt0rapzo/production/d19e06dcf4aff5a3eafd9d7b58c8703ea6e6b433.m4a",
"path": "files/zt0rapzo/production/d19e06dcf4aff5a3eafd9d7b58c8703ea6e6b433.m4a"
}
}
If you want to learn more about Sanity’s asset pipeline, you can go to the post we published in CSS-tricks a while back, and the documentation pages.
We hope you find it helpful, and if it has been, do tell us all about it over at the #i-made-this channel in our community slack.