|
#!/usr/bin/env babel-node --stage=0 |
|
|
|
import fs from 'fs'; |
|
import contentful from 'contentful-management'; |
|
import xtend from 'xtend'; |
|
|
|
const client = contentful.createClient({ |
|
// Get one by logging in at https://www.contentful.com/developers/documentation/content-management-api/ |
|
accessToken: 'CMA ACCESS TOKEN' |
|
}); |
|
|
|
const spaceId = 'YOUR SPACE ID'; |
|
|
|
async function main () { |
|
const space = await client.getSpace(spaceId); |
|
const assetLinkFields = await findAssetLinkFields(space); |
|
console.log(assetLinkFields); |
|
await walkAssets(space, maybeDeleteAsset.bind(null, space, assetLinkFields)) |
|
} |
|
|
|
async function findAssetLinkFields (space) { |
|
const contentTypes = await space.getContentTypes({}); |
|
|
|
return contentTypes.reduce((assetLinkFields, contentType) => { |
|
assetLinkFields[contentType.sys.id] = contentType.fields.filter(fieldIsAssetLink).map((field) => field.id) |
|
return assetLinkFields; |
|
}, {}); |
|
} |
|
|
|
function fieldIsAssetLink (field) { |
|
return (field.type === 'Link' && field.linkType === 'Asset') || |
|
(field.type === 'Array' && fieldIsAssetLink(field.items)) |
|
} |
|
|
|
async function walkAssets (space, fn) { |
|
const order = '-sys.createdAt' |
|
const limit = 1000; |
|
|
|
async function next (skip) { |
|
const items = await space.getAssets({ skip, limit, order }) |
|
await Promise.all(items.map(fn)) |
|
if (items.length === limit) { |
|
return next(skip + limit) |
|
} |
|
} |
|
|
|
return next(0); |
|
} |
|
|
|
async function maybeDeleteAsset (space, assetLinkFields, asset) { |
|
const id = asset.sys.id |
|
var linkCount = 0; |
|
for (var contentTypeId in assetLinkFields) { |
|
let fieldIds = assetLinkFields[contentTypeId]; |
|
|
|
for (var i = 0, len = fieldIds.length; i < len; i++) { |
|
let fieldId = fieldIds[i]; |
|
const entries = await space.getEntries({ |
|
content_type: contentTypeId, |
|
[`fields.${fieldId}.sys.id`]: asset.sys.id |
|
}) |
|
linkCount += entries.length; |
|
} |
|
} |
|
|
|
if (!linkCount) { |
|
// No links to this asset from the selected field, safe to delete |
|
if (asset.sys.publishedVersion) { |
|
asset = await space.unpublishAsset(asset); |
|
} |
|
await space.deleteAsset(asset); |
|
} |
|
} |
|
|
|
main().catch((err) => { |
|
console.error(err.stack); |
|
process.exit(1); |
|
}); |
In case you ended up here from google like me, and want to keep linked assets, edit
maybeDeleteAsset
to:@grncdr thanks a bunch for the snippet!