Espen Hovlandsdal
Open-sourceror @ Sanity.io
Script to find and delete unused assets in a dataset
// This script will find and delete all assets that are not
// referenced (in use) by other documents. Sometimes refered
// to as "orphaned" assets.
//
// Place this script somewhere and run it through
// `sanity exec <script-filename.js> --with-user-token`
/* eslint-disable no-console */
import {getCliClient} from 'sanity/cli'
const client = getCliClient({apiVersion: '2024-01-01'})
const query = `
*[_type in ["sanity.imageAsset", "sanity.fileAsset"]]
{_id, "refs": count(*[references(^._id)])}
[refs == 0]
._id
`
client
.fetch(query)
.then(ids => {
if (!ids.length) {
console.log('No assets to delete')
return true
}
console.log(`Deleting ${ids.length} assets`)
return ids
.reduce((trx, id) => trx.delete(id), client.transaction())
.commit({visibility: 'async'})
.then(() => console.log('Done!'))
})
.catch(err => {
if (err.message.includes('Insufficient permissions')) {
console.error(err.message)
console.error('Did you forget to pass `--with-user-token`?')
} else {
console.error(err.stack)
}
})
This script can be run with sanity exec deleteUnusedAssets.js --with-user-token
. It uses a GROQ query to count all incoming references to assets documents and filter out those referred to in another document. It takes the returned array of _id
s and builds a transaction of deletions.
It can be wise to export your dataset before running this script since it deletes data.
Open-sourceror @ Sanity.io
🚫 MyFile / ✅ MyFile.pdf
Go to Add extensions to asset original filenamesA script to validate that your schema is free of errors and warnings
Go to Validate schema scriptDrop this into your Studio to let editors know when there's a more recent version of your Studio available, making sure they have the latest fields and validations.
Go to Auto-reload Studio when changes are deployedScript to convert quotation marks in Portable Text blocks
Go to Convert quotation marks for Portable Text