contentful-management
Version:
Client for Contentful's Content Management API
93 lines (92 loc) • 3.18 kB
JavaScript
import { toPlainObject, freezeSys } from 'contentful-sdk-core';
import copy from 'fast-copy';
import enhanceWithMethods from '../enhance-with-methods';
import { wrapCursorPaginatedCollection } from '../common-utils';
const publicResourceTypeFields = ['name'];
/**
* @private
*/
function createResourceTypeApi(makeRequest) {
return {
/**
* Sends an update to the server with any changes made to the object's properties
* @return Object returned from the server with updated changes.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const client = contentful.createClient({
* accessToken: '<content_management_api_key>'
* })
*
* client.getOrganization('<org_id>')
* .then((org) => org.getAppDefinition('<app_def_id>'))
* .then((appDefinition) => appDefinition.getResourceType())
* .then((resourceType) => {
* resourceType.name = '<new_name>'
* return resourceType.upsert()
* })
* .catch(console.error)
* ```
*/
upsert: function upsert() {
const data = this.toPlainObject();
return makeRequest({
entityType: 'ResourceType',
action: 'upsert',
params: getParams(data),
headers: {},
payload: getUpsertParams(data)
}).then(data => wrapResourceType(makeRequest, data));
},
/**
* Deletes this object on the server.
* @return Promise for the deletion. It contains no data, but the Promise error case should be handled.
* @example ```javascript
* const contentful = require('contentful-management')
*
* const client = contentful.createClient({
* accessToken: '<content_management_api_key>'
* })
*
* client.getOrganization('<org_id>')
* .then((org) => org.getAppDefinition('<app_def_id>'))
* .then((appDefinition) => appDefinition.getResourceType())
* .then((resourceType) => resourceType.delete())
* .catch(console.error)
* ```
*/
delete: function del() {
const data = this.toPlainObject();
return makeRequest({
entityType: 'ResourceType',
action: 'delete',
params: getParams(data)
});
}
};
}
const getParams = data => ({
organizationId: data.sys.organization.sys.id,
appDefinitionId: data.sys.appDefinition.sys.id,
resourceTypeId: data.sys.id
});
const getUpsertParams = data => ({
name: data.name,
defaultFieldMapping: data.defaultFieldMapping
});
/**
* @private
* @param makeRequest - function to make requests via an adapter
* @param data - Raw Resource Type data
* @return Wrapped Resource Type data
*/
export function wrapResourceType(makeRequest, data) {
const resourceType = toPlainObject(copy(data));
const ResourceTypeWithMethods = enhanceWithMethods(resourceType, createResourceTypeApi(makeRequest));
return freezeSys(ResourceTypeWithMethods);
}
export function wrapResourceTypeforEnvironment(makeRequest, data) {
const resourceType = toPlainObject(data);
return freezeSys(resourceType);
}
export const wrapResourceTypesForEnvironmentCollection = wrapCursorPaginatedCollection(wrapResourceTypeforEnvironment);