@contentstack/management
Version:
The Content Management API is used to manage the content of your Contentstack account
387 lines (378 loc) • 15.3 kB
JavaScript
import _typeof from "@babel/runtime/helpers/typeof";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import cloneDeep from 'lodash/cloneDeep';
import { create, update, deleteEntity, fetch, query, upload, parseData } from '../../entity';
import { Entry } from './entry/index';
import error from '../../core/contentstackError';
import FormData from 'form-data';
import { createReadStream } from 'fs';
/**
* Content type defines the structure or schema of a page or a section of your web or mobile property. To create content for your application, you are required to first create a content type, and then create entries using the content type. Read more about <a href='https://www.contentstack.com/docs/guide/content-types'>Content Types</a>.
* @namespace ContentType
*/
export function ContentType(http) {
var _this = this;
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.stackHeaders = data.stackHeaders;
this.urlPath = "/content_types";
if (data.content_type) {
Object.assign(this, cloneDeep(data.content_type));
this.urlPath = "/content_types/".concat(this.uid);
/**
* @description The Update ContentType call lets you update the name and description of an existing ContentType.
* You can also update the JSON schema of a content type, including fields and different features associated with the content type.
* @memberof ContentType
* @func update
* @returns {Promise<ContentType>} Promise for ContentType instance
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').fetch()
* .then((contentType) => {
* contentType.title = 'My New Content Type'
* contentType.description = 'Content Type description'
* return contentType.update()
* })
* .then((contentType) => console.log(contentType))
*
*/
this.update = update(http, 'content_type');
/**
* @description The Update ContentType call lets you update the name and description of an existing ContentType.
* You can also update the JSON schema of a content type, including fields and different features associated with the content type.
* @memberof ContentType
* @func updateCT
* @async
* @param {Object} config - Content type configuration object containing the content_type object with updated fields.
* @returns {Promise<Object>} Response Object.
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
* const data = {
* "content_type": {
* "title": "Page",
* "uid": "page",
* "schema": [{
* "display_name": "Title",
* "uid": "title",
* "data_type": "text",
* "field_metadata": {
* "_default": true
* },
* "unique": false,
* "mandatory": true,
* "multiple": false
* }
* ],
* "options": {
* "title": "title",
* "publishable": true,
* "is_page": true,
* "singleton": false,
* "sub_title": [
* "url"
* ],
* "url_pattern": "/:title",
* "url_prefix": "/"
* }
* }
* }
* }
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').updateCT(data)
* .then((response) => {
* console.log(response)
* })
*/
this.updateCT = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(config) {
var headers, response, _t;
return _regeneratorRuntime.wrap(function (_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
headers = {
headers: _objectSpread({}, cloneDeep(_this.stackHeaders))
};
_context.next = 1;
return http.put("".concat(_this.urlPath), config, headers);
case 1:
response = _context.sent;
if (!response.data) {
_context.next = 2;
break;
}
return _context.abrupt("return", response.data);
case 2:
throw error(response);
case 3:
_context.next = 5;
break;
case 4:
_context.prev = 4;
_t = _context["catch"](0);
throw error(_t);
case 5:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 4]]);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}();
/**
* @description The Delete ContentType call is used to delete an existing ContentType permanently from your Stack.
* @memberof ContentType
* @func delete
* @returns {Promise<Object>} Response Object.
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').delete()
* .then((response) => console.log(response.notice))
*/
this["delete"] = deleteEntity(http);
/**
* @description The fetch ContentType call fetches ContentType details.
* @memberof ContentType
* @func fetch
* @returns {Promise<ContentType>} Promise for ContentType instance
* @param {Object=} param - Query parameters
* @prop {Int} param.version - Enter the version number of the content type you want to retrieve.
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').fetch()
* .then((contentType) => console.log(contentType))
*
*/
this.fetch = fetch(http, 'content_type');
/**
* @description Entry defines the actual piece of content created using one of the defined content types.
* @param {String=} uid - The UID of the Entry you want to get details.
* @param {Object} options - Optional configuration object.
* @prop {string} options.api_version - API version to use for the request.
* @returns {Entry} Instance of Entry.
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('entry_uid').fetch()
* .then((entry) => console.log(entry))
*/
this.entry = function () {
var uid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var data = {
stackHeaders: _this.stackHeaders
};
data.content_type_uid = _this.uid;
if (uid) {
data.entry = {
uid: uid
};
}
options = options || {}; // Ensure `options` is always an object
if (options && _typeof(options) === 'object' && options.api_version) {
data.api_version = options.api_version;
}
return new Entry(http, data);
};
/**
* @description References call will fetch all the content types in which a specified content type is referenced.
* @async
* @returns {Promise<Object>} Promise for ContentType references
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType('content_type_uid').references()
* .then((contentType) => console.log(contentType))
*/
this.references = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
var headers, response, _t2;
return _regeneratorRuntime.wrap(function (_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
headers = {
headers: _objectSpread({}, cloneDeep(_this.stackHeaders))
};
_context2.next = 1;
return http.get("/content_types/".concat(_this.uid, "/references"), headers);
case 1:
response = _context2.sent;
if (!response.data) {
_context2.next = 2;
break;
}
return _context2.abrupt("return", response.data);
case 2:
throw error(response);
case 3:
_context2.next = 5;
break;
case 4:
_context2.prev = 4;
_t2 = _context2["catch"](0);
throw error(_t2);
case 5:
case "end":
return _context2.stop();
}
}, _callee2, null, [[0, 4]]);
}));
} else {
/**
* @description The Create a content type call creates a new content type in a particular stack of your Contentstack account.
* @memberof ContentType
* @func generateUid
* @param {*} name Name for content type you want to create.
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
* const contentType = client.stack().contentType()
* const contentTypeName = 'My New contentType'
* const content_type = {
* name: name,
* uid: contentType.generateUid(name)
* }
* contentType
* .create({ content_type })
* .then((contenttype) => console.log(contenttype))
*
*/
this.generateUid = function (name) {
if (!name) {
throw new TypeError('Expected parameter name');
}
return name.replace(/[^A-Z0-9]+/gi, '_').toLowerCase();
};
/**
* @description The Create a content type call creates a new content type in a particular stack of your Contentstack account.
* @memberof ContentType
* @func create
* @returns {Promise<ContentType>} Promise for ContentType instance
*
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
* const content_type = {name: 'My New contentType'}
* client.stack().contentType().create({ content_type })
* .then((contentType) => console.log(contentType))
*/
this.create = create({
http: http
});
/**
* @description The Query on Content Type will allow you to fetch details of all or specific Content Types.
* @memberof ContentType
* @func query
* @param {Boolean} include_count Set this to 'true' to include in response the total count of content types available in your stack.
* @returns {Object} Query builder object with find(), count(), and findOne() methods.
*
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* client.stack({ api_key: 'api_key'}).contentType().query({ query: { name: 'Content Type Name' } }).find()
* .then((contentTypes) => console.log(contentTypes))
*/
this.query = query({
http: http,
wrapperCollection: ContentTypeCollection
});
/**
* @description The Import a content type call imports a content type into a stack.
* @memberof ContentType
* @func import
* @async
* @param {Object} data - Import data object.
* @prop {string} data.content_type - Path to content type file.
* @param {Object=} params - Optional request parameters.
* @returns {Promise<ContentType>} Promise for ContentType instance
* @example
* import * as contentstack from '@contentstack/management'
* const client = contentstack.client()
*
* const data = {
* content_type: 'path/to/file.json',
* }
* client.stack({ api_key: 'api_key'}).contentType().import(data, { overwrite: true })
* .then((contentType) => console.log(contentType))
*
*/
this["import"] = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(data) {
var params,
response,
_args3 = arguments,
_t3;
return _regeneratorRuntime.wrap(function (_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
params = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
_context3.prev = 1;
_context3.next = 2;
return upload({
http: http,
urlPath: "".concat(this.urlPath, "/import"),
stackHeaders: this.stackHeaders,
formData: createFormData(data),
params: params
});
case 2:
response = _context3.sent;
if (!response.data) {
_context3.next = 3;
break;
}
return _context3.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders)));
case 3:
throw error(response);
case 4:
_context3.next = 6;
break;
case 5:
_context3.prev = 5;
_t3 = _context3["catch"](1);
throw error(_t3);
case 6:
case "end":
return _context3.stop();
}
}, _callee3, this, [[1, 5]]);
}));
return function (_x2) {
return _ref3.apply(this, arguments);
};
}();
}
return this;
}
export function ContentTypeCollection(http, data) {
var obj = cloneDeep(data.content_types) || [];
var contentTypeCollection = obj.map(function (userdata) {
return new ContentType(http, {
content_type: userdata,
stackHeaders: data.stackHeaders
});
});
return contentTypeCollection;
}
export function createFormData(data) {
return function () {
var formData = new FormData();
var uploadStream = createReadStream(data.content_type);
formData.append('content_type', uploadStream);
return formData;
};
}