Edits history of script submission #8986 for ' Create Record (contentful)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import Contentful from 'contentful-management'
    
    type Contentful = {
    	accessToken: string
    	environment: string
    	spaceId: string
    }
    
    const makeClient = (resource: Contentful) => {
    	return Contentful.createClient(
    		{ accessToken: resource.accessToken },
    		{
    			type: 'plain',
    			defaults: { spaceId: resource.spaceId, environmentId: resource.environment }
    		}
    	)
    }
    
    // Utility function to key an array by a specific key
    function keyBy<T>(array: T[], key: keyof T): { [key: string]: T } {
    	return (array || []).reduce((result, item) => {
    		const keyValue = key ? item[key] : (item as unknown as string)
    		result[keyValue as unknown as string] = item
    		return result
    	}, {} as { [key: string]: T })
    }
    
    type FieldProcessor = (field: Contentful.ContentFields, value: any) => any
    
    const FieldProcessors: Record<string, FieldProcessor> = {
    	Link: (field, value) => {
    		return {
    			sys: {
    				type: 'Link',
    				linkType: field.linkType,
    				id: value
    			}
    		}
    	},
    	Array: (field, value) => {
    		if (field.items?.type === 'Symbol') {
    			return value
    		}
    		if (field.items?.type === 'Link') {
    			return value.map((v: string) => ({
    				sys: {
    					type: 'Link',
    					linkType: field.items?.linkType,
    					id: v
    				}
    			}))
    		}
    	},
    	Basic: (field, value) => value
    }
    
    export async function main(
    	resource: Contentful,
    	metadata: {
    		locale: string
    		contentTypeId: string
    		publishOnCreate: boolean
    		fields: Record<string, any>
    	}
    ) {
    	const client = makeClient(resource)
    
    	const model = await client.contentType.get({
    		contentTypeId: metadata.contentTypeId
    	})
    
    	const fields = keyBy(model.fields, 'id')
    	const values = metadata.fields
    
    	// Remove empty fields and process values
    	for (const key in values) {
    		if (
    			values[key] === '' ||
    			values[key] === null ||
    			values[key] === undefined ||
    			(Array.isArray(values[key]) && values[key].length === 0)
    		) {
    			delete values[key]
    			continue
    		}
    		const fieldType = fields[key].type
    		const processor = FieldProcessors[fieldType] || FieldProcessors['Basic']
    		values[key] = {
    			[metadata.locale]: await processor(fields[key], values[key])
    		}
    	}
    
    	const record = await client.entry.create({ contentTypeId: model.sys.id }, { fields: values })
    
    	if (metadata.publishOnCreate) {
    		await client.entry.publish({ entryId: record.sys.id }, record)
    	}
    
    	return record
    }
    

    Submitted by hugo697 650 days ago