Created
September 6, 2023 21:33
-
-
Save adgang/1d83d1845476a291ff2106e6def0ef76 to your computer and use it in GitHub Desktop.
A portable script(works with different versions of directus) to add system fields to existing collection in directus
This file contains 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
import { | |
createDirectus, | |
createField, | |
readFields, | |
rest, | |
staticToken, | |
} from '@directus/sdk'; | |
/** | |
* The collection on which you need system fields | |
*/ | |
const collection = 'another_sample_collection'; | |
/** | |
* Create a new collection with system fields in it. | |
*/ | |
const collectionWithSystemFields = 'some_collection_with_system_fields'; | |
/** | |
* Select which of the system fields you need on your collection. | |
*/ | |
const systemFieldNames = [ | |
'status', | |
'sort', | |
'date_created', | |
'date_updated', | |
'user_created', | |
'user_updated', | |
]; | |
const prodDirectus = createDirectus(PRODUCTION_URL) | |
.with(rest()) | |
.with(staticToken(PRODUCTION_CMS_TOKEN)); | |
async function addSystemFields() { | |
const fields = await prodDirectus.request(readFields()); | |
const fieldsToCopy = fields | |
.filter((f) => f.collection === collectionWithSystemFields) | |
.filter((f) => systemFieldNames.includes(f.field)); | |
const fieldsToPaste = fieldsToCopy.map((f) => { | |
const { schema, meta } = f; | |
const { id, ...restOfMeta } = meta; | |
return { | |
...f, | |
collection, | |
schema: { ...schema, table: collection }, | |
meta: { ...restOfMeta, collection }, | |
}; | |
}); | |
for (let field of fieldsToPaste) { | |
try { | |
const promise = await prodDirectus.request( | |
createField(collection, field), | |
); | |
console.log(`added field ${field.field} to ${collection}`); | |
} catch (err) { | |
console.log(`error adding a field ${field.field} to ${collection}:`, err); | |
} | |
} | |
} | |
addSystemFields(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment