forked from sanity-io/sanity-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deleteUnusedAssets.js
38 lines (34 loc) · 1.01 KB
/
deleteUnusedAssets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 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 client from 'part:@sanity/base/client'
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()
.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)
}
})