Created
April 16, 2025 17:54
-
-
Save jwatney/f1ea8ff3085c957a288eac898ee14833 to your computer and use it in GitHub Desktop.
Delete unreferenced assets in Sanity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This migration will delete all unused assets from the targeted Sanity dataset | |
*/ | |
import { defineQuery } from 'groq' | |
import { defineMigration, delete_ } from 'sanity/migrate' | |
const unrefedAssets = defineQuery(`*[_type in ['sanity.imageAsset', 'sanity.fileAsset']] { | |
_id, | |
'refs': count(*[references(^._id)]) | |
}[refs == 0][$start..$end]._id`) | |
function createPager() { | |
const size = 50 | |
const page = { | |
start: 0, | |
end: size - 1, | |
} | |
function increment() { | |
page.start += size | |
page.end += size | |
} | |
return { | |
page, | |
increment, | |
} | |
} | |
export default defineMigration({ | |
title: 'Delete unused files', | |
async *migrate(_, context) { | |
const { page, increment } = createPager() | |
while (true) { | |
const results = await context.client.fetch(unrefedAssets, page) | |
if (results.length == 0) { | |
break | |
} | |
for (const id of results) { | |
yield delete_(id) | |
} | |
increment() | |
} | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment