diff --git a/.babel-preset.js b/.babel-preset.js new file mode 100644 index 00000000..d78df41b --- /dev/null +++ b/.babel-preset.js @@ -0,0 +1,14 @@ +var plugins = [ + 'transform-object-rest-spread', + 'lodash', + ['inline-replace-variables', { + // Inject version number into code + '__VERSION__': require('./package.json').version + }] + ] + + +function babelConfig () { + return plugins +} +module.exports = babelConfig diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..c1e169da --- /dev/null +++ b/.babelrc @@ -0,0 +1,34 @@ +{ + "presets": ["@babel/preset-env"], + "plugins": [ + ["@babel/plugin-transform-runtime", { + "regenerator": true + }] + ], + "env": { + "test": { + "presets": [ + ["@babel/env"] + ], + "plugins": ["rewire"], + "sourceMaps": "inline" + }, + "es5": { + "presets": [ + ["@babel/env"] + ], + "plugins": [ + "add-module-exports", + "@babel/plugin-transform-runtime", + "transform-es2015-modules-commonjs" + ] + }, + "es-modules": { + "presets": [ + ["@babel/env", { + "modules": false + }] + ] + } + } +} \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 00000000..1c0a39d7 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,24 @@ +module.exports = { + // "env": { + // "browser": true, + // "amd": true + // }, + "extends": "standard", + // "globals": { + // "Atomics": "readonly", + // "SharedArrayBuffer": "readonly" + // }, + // "parserOptions": { + // "ecmaFeatures": { + // "jsx": true + // }, + // "ecmaVersion": 2015, + // "sourceType": "module" + // }, + 'plugins': [ + 'standard', + 'promise' + ], + "rules": { + } +}; \ No newline at end of file diff --git a/.gitignore b/.gitignore index ad46b308..a9693d3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Logs logs *.log +*.DS_Store npm-debug.log* yarn-debug.log* yarn-error.log* @@ -35,10 +36,14 @@ build/Release # Dependency directories node_modules/ jspm_packages/ +jsdocs/ +mochawesome-report/ +coverage/ +test/utility/dataFiles/ # TypeScript v1 declaration files typings/ - +tsconfig.json # Optional npm cache directory .npm diff --git a/.jsdoc.json b/.jsdoc.json new file mode 100644 index 00000000..0ba42df0 --- /dev/null +++ b/.jsdoc.json @@ -0,0 +1,47 @@ +{ + "tags": { + "allowUnknownTags": true, + "dictionaries": ["jsdoc"] + }, + "source": { + "include": [ + "lib/contentstack.js", + "lib/contentstackClient.js", + "lib/user/index.js", + "lib/organization/index.js", + "lib/stack/index.js", + "lib/stack/contentType/index.js", + "lib/stack/globalField/index.js", + "lib/query/index.js", + "lib/stack/contentType/entry/index.js", + "lib/stack/asset/index.js", + "lib/stack/asset/folders/index.js", + "lib/stack/bulkOperation/index.js", + "lib/stack/extension/index.js", + "lib/stack/release/index.js", + "lib/stack/label/index.js", + "lib/stack/locale/index.js", + "lib/stack/environment/index.js", + "lib/stack/deliveryToken/index.js", + "lib/stack/roles/index.js", + "lib/stack/webhook/index.js" + ], + "excludePattern": "(node_modules/|jsdocs)" + }, + "templates": { + "cleverLinks": false, + "monospaceLinks": true + }, + "opts": { + "destination": "./jsdocs/", + "encoding": "utf8", + "private": true, + "recurse": true, + "template": "./node_modules/docdash", + "sort": false + }, + "docdash": { + "static": true, + "sort": false + } +} \ No newline at end of file diff --git a/.npmignore b/.npmignore new file mode 100644 index 00000000..e90aaefc --- /dev/null +++ b/.npmignore @@ -0,0 +1,17 @@ +docs-config.json +.idea/ +.git/ +test/ +reports/ +contentstack-templates/ +jsdocs/ +examples/ +mocktest.json +Sample +coverage/ +mochawesome-report/ +.nyc_output/ +typings +webpack/ +tsconfig.json +.jsdoc.json \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..a3d4c3c9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +## [v1.0.0](https://github.com/contentstack/contentstack-management-javascript/tree/v1.0.0) (2020-09-23) + - Initial release for Contentstack CMA base JS management SDK diff --git a/README.md b/README.md index 890146ae..bb733ee5 100644 --- a/README.md +++ b/README.md @@ -1 +1,113 @@ -# contentstack-management-javascript \ No newline at end of file +[![Contentstack](https://www.contentstack.com/docs/static/images/contentstack.png)](https://www.contentstack.com/) + +## Contentstack Management JavaScript SDK + +Contentstack is a headless CMS with an API-first approach. It is a CMS that developers can use to build powerful cross-platform applications in their favorite languages. All you have to do is build your application frontend, and Contentstack will take care of the rest. [Read More](https://www.contentstack.com/). + +This SDK uses the [Content Management API](https://www.contentstack.com/docs/developers/apis/content-management-api/) (CMA). The CMA is used to manage the content of your Contentstack account. This includes creating, updating, deleting, and fetching content of your account. To use the CMA, you will need to authenticate your users with a [Management Token](https://www.contentstack.com/docs/developers/create-tokens/about-management-tokens) or an [Authtoken](https://www.contentstack.com/docs/developers/apis/content-management-api/#how-to-get-authtoken). Read more about it in [Authentication](https://www.contentstack.com/docs/developers/apis/content-management-api/#authentication). + +Note: By using CMA, you can execute GET requests for fetching content. However, we strongly recommend that you always use the [Content Delivery API](https://www.contentstack.com/docs/developers/apis/content-delivery-api/) to deliver content to your web or mobile properties. + +### Prerequisite + +You need Node.js version 10 or above installed on your machine to use the Contentstack JavaScript CMA SDK. + +### Installation +#### Node +Install it via npm: +```bash +npm i @contentstack/management +``` +To import the SDK, use the following command: +``` +import contentstack from ‘@contentstack/management’ + +contentstackClient = contentstack.client() +``` + +### Authentication +To use this SDK, you need to authenticate your users by using the Authtoken, credentials, or Management Token (stack-level token). +### Authtoken +An [Authtoken](https://www.contentstack.com/docs/developers/create-tokens/types-of-tokens/#authentication-tokens-authtokens-) is a read-write token used to make authorized CMA requests, and it is a **user-specific** token. +``` +contentstackClient = contentstack.client({ authtoken: 'AUTHTOKEN' }) +``` +### Login +To Login to Contentstack by using credentials, you can use the following lines of code: +``` +contentstackClient.login({ email: 'EMAIL', password: 'PASSWORD'}) +.then((response) => { + console.log(response.notice) + console.log(response.user) +}) +``` + +### Management Token +[Management Tokens](https://www.contentstack.com/docs/developers/create-tokens/about-management-tokens/) are **stack-level** tokens, with no users attached to them. +``` +contentstackClient.stack({ api_key: 'API_KEY', management_token: 'MANAGEMENT_TOKEN' }) +.fetch() +.then((stack) => { + console.log(stack) +}) +``` +### Contentstack Management JavaScript SDK: 5-minute Quickstart +#### Initializing Your SDK: +To use the JavaScript CMA SDK, you need to first initialize it. To do this, use the following code: +``` +import contentstack from ‘@contentstack/management’ + +var contentstackClient = contentstack.client({ authtoken: 'AUTHTOKEN' }) +``` +#### Fetch Stack Detail +Use the following lines of code to fetch your stack detail using this SDK: +``` +contentstackClient.stack({ api_key: 'API_KEY' }) +.fetch() +.then((stack) => { + console.log(stack) +}) +``` + +#### Create Entry +To create an entry in a specific content type of a stack, use the following lines of code: +``` +var entry = { + title: 'Sample Entry', + url: '/sampleEntry' +} + +contentstackClient.stack({ api_key: 'API_KEY' }).contentType('CONTENT_TYPE_UID').entry().create({ entry }) +.then((entry) => { + console.log(entry) +}) +``` + +#### Create Asset +The following lines of code can be used to upload assets to your stack: +``` +var asset = { + upload: 'path/to/file', + title: 'Asset Title' +} + +contentstackClient.stack({ api_key: 'API_KEY' }).asset().create({ asset }) +.then((asset) => { + console.log(asset) +}) +``` + +### Helpful Links + +- [Contentstack Website](https://www.contentstack.com/) +- [Official Documentation](https://contentstack.com/docs) +- [Content Management API Docs](https://www.contentstack.com/docs/developers/apis/content-management-api) + +### The MIT License (MIT) +Copyright © 2012-2020 [Contentstack](https://www.contentstack.com/). All Rights Reserved + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/dist/es-modules/contentstack.js b/dist/es-modules/contentstack.js new file mode 100644 index 00000000..cdb3c515 --- /dev/null +++ b/dist/es-modules/contentstack.js @@ -0,0 +1,140 @@ +import _defineProperty from "@babel/runtime/helpers/defineProperty"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +/** + * The Content Management API (CMA) is used to manage the content of your Contentstack account. This includes creating, updating, deleting, and fetching content of your account. + * @namespace Contentstack + */ +import packages from '../package.json'; +import clonedeep from 'lodash/cloneDeep'; +import getUserAgent from './core/Util.js'; +import contentstackClient from './contentstackClient.js'; +import httpClient from './core/contentstackHTTPClient.js'; +/** + * Create client instance + * @name client + * @memberof Contentstack + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * @param {object} params - Client initialization parameters + * @param {Object=} param.proxy - + * @prop {string=} params.endpoint - API endpoint that a service will talk to + * @example //Set the `endpoint` to 'https://api.contentstack.io:{port}/{version}' + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ endpoint: 'https://api.contentstack.io:{port}/{version}' }) + * + * @prop {string=} params.host - API host (default: api.contentstack.io) + * @example //Set the `host` to 'api.contentstack.io' + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ host: 'api.contentstack.io' }) + * + * @prop {object=} params.headers - Optional additional headers + * @example //Set the `headers` to { 'headerkey': 'value'} + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ headers: { 'headerkey': 'value'} }) + * + * @prop {number=} params.timeout - Optional number of milliseconds before the request times out. Default is 30000ms + * @example //Set the `timeout` to 50000ms + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ timeout: 50000 }) + * + * @prop {boolean=} params.retryOnError - Optional boolean for retry on failuer. Default is true + * @example //Set the `retryOnError` to false + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ retryOnError: false }) + * + * @prop {number=} params.retryLimit - Optional number of retries before failure. Default is 5 + * @example //Set the `retryLimit` to 2 + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ retryLimit: 2 }) + * + * @prop {number=} params.retryDelay - The number of miliseconds to use for operation retries. Default is 300ms + * @example //Set the `retryDelay` to 500ms + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ retryDelay: 500 }) + * + * @prop {Function=} params.retryCondition - A function to determine if the error can be retried. Default retry is on status 429. + * @example //Set the `retryCondition` on error status 429 + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ retryCondition: (error) => { + * if (error.response && error.response.status === 429) { + * return true + * } + * return false + * } + * }) + * + * @prop {number=} params.retryDelayOptions.base - The base number of milliseconds to use in the exponential backoff for operation retries. + * @example Set base retry delay for all services to 300 ms + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({retryDelayOptions: {base: 300}}) + * + * @prop {Function=} params.retryDelayOptions.customBackoff - A custom function that accepts a retry count and error and returns the amount of time to delay in milliseconds. (if you want not to retry for specific condition return -1) + * @example Set a custom backoff function to provide delay of 500 ms on retryCount < 3 and -1 for retryCount >= 3values on retries + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({retryDelayOptions: {customBackoff: function(retryCount, err) { + * if (retryCount < 3) { + * return 500 + * } else { + * return -1 //returning -1 will hold next retry for request + * } + * }}} + * ) + * + * @prop {number=} params.maxContentLength - Optional maximum content length in bytes (default: 1073741824 i.e. 1 GB) + * @example //Set the `maxContentLength` to 1024 ** 3 + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ maxContentLength: 1024 ** 3 }) + * + * @prop {number=} params.maxBodyLength - Optional maximum body length in bytes (default: 10 MB) + * @example //Set the `maxContentLength` to 1024 ** 2 * 10 // 10 MB + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ maxBodyLength: 1024 ** 2 * 10 }) + * + * @prop {function=} params.logHandler - A log handler function to process given log messages & errors. + * @example //Set the `logHandler` + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client({ logHandler: (level, data) => { + if (level === 'error' && data) { + const title = [data.name, data.message].filter((a) => a).join(' - ') + console.error(`[error] ${title}`) + return + } + console.log(`[${level}] ${data}`) + } }) + * + * @prop {string=} params.application - Application name and version e.g myApp/version + * @prop {string=} params.integration - Integration name and version e.g react/version + * @returns Contentstack.Client + */ + +export function client() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaultParameter = { + defaultHostName: 'api.contentstack.io' + }; + var sdkAgent = "".concat(packages.name, "-javascript/").concat(packages.version); + var userAgentHeader = getUserAgent(sdkAgent, params.application, params.integration, params.feature); + var requiredHeaders = { + 'X-User-Agent': sdkAgent, + 'User-Agent': userAgentHeader + }; + + if (params.authtoken) { + requiredHeaders.authtoken = params.authtoken; + } + + params = _objectSpread(_objectSpread({}, defaultParameter), clonedeep(params)); + params.headers = _objectSpread(_objectSpread({}, params.headers), requiredHeaders); + var http = httpClient(params); + var api = contentstackClient({ + http: http + }); + return api; +} \ No newline at end of file diff --git a/dist/es-modules/contentstackClient.js b/dist/es-modules/contentstackClient.js new file mode 100644 index 00000000..e8ae5a53 --- /dev/null +++ b/dist/es-modules/contentstackClient.js @@ -0,0 +1,198 @@ +import _defineProperty from "@babel/runtime/helpers/defineProperty"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +/** + * @namespace ContentstackClient + */ +import { Stack } from './stack/index.js'; +import { Organization } from './organization/index'; +import cloneDeep from 'lodash/cloneDeep'; +import { User } from './user/index'; +import error from './core/contentstackError'; +export default function contentstackClient(_ref) { + var http = _ref.http; + + /** + * @description The Log in to your account request is used to sign in to your Contentstack account and obtain the authtoken. + * @memberof ContentstackClient + * @func login + * @param {Object} parameters - login parameters + * @prop {string} paramters.email - email id for user to login + * @prop {string} paramters.password - password for user to login + * @prop {string} paramters.token - token for user to login + * @returns {Promise} + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.login({ email: , password: }) + * .then(() => console.log('Logged in successfully')) + * + */ + function login(requestBody) { + var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return http.post('/user-session', { + user: requestBody + }, { + params: params + }).then(function (response) { + if (response.data.user != null && response.data.user.authtoken != null) { + http.defaults.headers.common.authtoken = response.data.user.authtoken; + response.data.user = new User(http, response.data); + } + + return response.data; + }, error); + } + /** + * @description The Get user call returns comprehensive information of an existing user account. + * The information returned includes details of the stacks owned by and shared with the specified user account. + * @memberof ContentstackClient + * @func getUser + * @returns {Promise} + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.getUser() + * .then((user) => console.log(user)) + * + */ + + + function getUser() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return http.get('/user', { + params: params + }).then(function (response) { + return new User(http, response.data); + }, error); + } + /** + * @description Get Stack instance. A stack is a space that stores the content of a project. + * @memberof ContentstackClient + * @func stack + * @param {String} api_key - Stack API Key + * @param {String} management_token - Stack API Key + * @returns {Stack} Instance of Stack + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const stack = {name: 'My New Stack'} + * client.stack().create({ stack }, { organization_uid: 'org_uid' }) + * .then((stack) => console.log(stack)) + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).fetch() + * .then((stack) => console.log(stack)) + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key', management_token: 'management_token' }).fetch() + * .then((stack) => console.log(stack)) + * + */ + + + function stack() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + var stack = _objectSpread({}, cloneDeep(params)); + + return new Stack(http, { + stack: stack + }); + } + /** + * @description Organization is the top-level entity in the hierarchy of Contentstack, consisting of stacks and stack resources, and users. + * @memberof ContentstackClient + * @func organization + * @param {String} uid - Organization UID. + * @returns {Organization} Instance of Organization. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization().findAll() + * .then((organization) => console.log(organization)) + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('org_uid').fetch() + * .then((organization) => console.log(organization)) + * + */ + + + function organization() { + var uid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + return new Organization(http, uid !== null ? { + organization: { + uid: uid + } + } : null); + } + /** + * @description The Log out of your account call is used to sign out the user of Contentstack account. + * @memberof ContentstackClient + * @param {String} authtoken - Authtoken to logout from. + * @func logout + * @returns {Object} Response object. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * client.logout() + * .then((response) => console.log(response)) + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * client.logout('AUTHTOKEN') + * .then((response) => console.log(response)) + * */ + + + function logout(authtoken) { + if (authtoken !== undefined) { + return http["delete"]('/user-session', { + headers: { + authtoken: authtoken + } + }).then(function (response) { + return response.data; + }, error); + } + + return http["delete"]('/user-session').then(function (response) { + if (http.defaults.headers.common) { + delete http.defaults.headers.common.authtoken; + } + + delete http.defaults.headers.authtoken; + delete http.httpClientParams.authtoken; + delete http.httpClientParams.headers.authtoken; + return response.data; + }, error); + } + + return { + login: login, + logout: logout, + getUser: getUser, + stack: stack, + organization: organization + }; +} \ No newline at end of file diff --git a/dist/es-modules/contentstackCollection.js b/dist/es-modules/contentstackCollection.js new file mode 100644 index 00000000..292cc6aa --- /dev/null +++ b/dist/es-modules/contentstackCollection.js @@ -0,0 +1,34 @@ +import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; + +var ContentstackCollection = function ContentstackCollection(response, http) { + var stackHeaders = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + var wrapperCollection = arguments.length > 3 ? arguments[3] : undefined; + + _classCallCheck(this, ContentstackCollection); + + var data = response.data || {}; + + if (stackHeaders) { + data.stackHeaders = stackHeaders; + } + + this.items = wrapperCollection(http, data); + + if (data.schema !== undefined) { + this.schema = data.schema; + } + + if (data.content_type !== undefined) { + this.content_type = data.content_type; + } + + if (data.count !== undefined) { + this.count = data.count; + } + + if (data.notice !== undefined) { + this.notice = data.notice; + } +}; + +export { ContentstackCollection as default }; \ No newline at end of file diff --git a/dist/es-modules/core/Util.js b/dist/es-modules/core/Util.js new file mode 100644 index 00000000..79c5418f --- /dev/null +++ b/dist/es-modules/core/Util.js @@ -0,0 +1,105 @@ +import { platform, release } from 'os'; +var HOST_REGEX = /^(?!\w+:\/\/)([\w-:]+\.)+([\w-:]+)(?::(\d+))?(?!:)$/; +export function isHost(host) { + return HOST_REGEX.test(host); +} +export function isNode() { + return typeof process !== 'undefined' && !process.browser; +} +export function getNodeVersion() { + return process.versions.node ? "v".concat(process.versions.node) : process.version; +} + +function isReactNative() { + return typeof window !== 'undefined' && 'navigator' in window && 'product' in window.navigator && window.navigator.product === 'ReactNative'; +} + +function getBrowserOS() { + if (!window) { + return null; + } + + var userAgent = window.navigator.userAgent; + var platform = window.navigator.platform; + var macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K']; + var windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE']; + var iosPlatforms = ['iPhone', 'iPad', 'iPod']; + var os = null; + + if (macosPlatforms.indexOf(platform) !== -1) { + os = 'macOS'; + } else if (iosPlatforms.indexOf(platform) !== -1) { + os = 'iOS'; + } else if (windowsPlatforms.indexOf(platform) !== -1) { + os = 'Windows'; + } else if (/Android/.test(userAgent)) { + os = 'Android'; + } else if (/Linux/.test(platform)) { + os = 'Linux'; + } + + return os; +} + +function getNodeOS() { + var os = platform() || 'linux'; + var version = release() || '0.0.0'; + var osMap = { + android: 'Android', + aix: 'Linux', + darwin: 'macOS', + freebsd: 'Linux', + linux: 'Linux', + openbsd: 'Linux', + sunos: 'Linux', + win32: 'Windows' + }; + + if (os in osMap) { + return "".concat(osMap[os] || 'Linux', "/").concat(version); + } + + return null; +} + +export default function getUserAgent(sdk, application, integration, feature) { + var headerParts = []; + + if (application) { + headerParts.push("app ".concat(application)); + } + + if (integration) { + headerParts.push("integration ".concat(integration)); + } + + if (feature) { + headerParts.push('feature ' + feature); + } + + headerParts.push("sdk ".concat(sdk)); + var os = null; + + try { + if (isReactNative()) { + os = getBrowserOS(); + headerParts.push('platform ReactNative'); + } else if (isNode()) { + os = getNodeOS(); + headerParts.push("platform node.js/".concat(getNodeVersion())); + } else { + os = getBrowserOS(); + headerParts.push("platform browser"); + } + } catch (e) { + os = null; + } + + if (os) { + headerParts.push("os ".concat(os)); + } + + return "".concat(headerParts.filter(function (item) { + return item !== ''; + }).join('; '), ";"); +} \ No newline at end of file diff --git a/dist/es-modules/core/contentstack-retry.js b/dist/es-modules/core/contentstack-retry.js new file mode 100644 index 00000000..e0a6d74a --- /dev/null +++ b/dist/es-modules/core/contentstack-retry.js @@ -0,0 +1,86 @@ +export default function contentstckRetry(axios, defaultOptions) { + var retryLimit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 5; + var retryDelay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkError = 0; + axios.interceptors.request.use(function (config) { + if (config.headers.authorization && config.headers.authorization !== undefined) { + delete config.headers.authtoken; + } + + return config; + }); + axios.interceptors.response.use(function (response) { + return response; + }, function (error) { + var wait = retryDelay; + var retryErrorType = null; + + if (!defaultOptions.retryOnError) { + return Promise.reject(error); + } + + var response = error.response; + + if (!response) { + retryErrorType = "Server connection"; + return Promise.reject(error); + } + + if (defaultOptions.retryCondition && defaultOptions.retryCondition(error)) { + retryErrorType = "Error with status: ".concat(error.response.status); + networkError++; + + if (networkError > retryLimit) { + networkError = 0; + return Promise.reject(error); + } + + if (defaultOptions.retryDelayOptions) { + if (defaultOptions.retryDelayOptions.customBackoff) { + wait = defaultOptions.retryDelayOptions.customBackoff(networkError, error); + + if (wait && wait <= 0) { + networkError = 0; + return Promise.reject(error); + } + } else if (defaultOptions.retryDelayOptions.base) { + wait = defaultOptions.retryDelayOptions.base * networkError; + } + } else { + wait = retryDelay; + } + } else { + networkError = 0; + } + + if (retryErrorType && error.config !== undefined) { + var config = error.config; + defaultOptions.logHandler('warning', "".concat(retryErrorType, " error occurred. Waiting for ").concat(wait, " ms before retrying...")); + + if (axios !== undefined && axios.defaults !== undefined) { + if (axios.defaults.agent === config.agent) { + delete config.agent; + } + + if (axios.defaults.httpAgent === config.httpAgent) { + delete config.httpAgent; + } + + if (axios.defaults.httpsAgent === config.httpsAgent) { + delete config.httpsAgent; + } + } + + config.transformRequest = [function (data) { + return data; + }]; + return new Promise(function (resolve) { + return setTimeout(function () { + return resolve(axios(config)); + }, wait); + }); + } + + return Promise.reject(error); + }); +} \ No newline at end of file diff --git a/dist/es-modules/core/contentstackError.js b/dist/es-modules/core/contentstackError.js new file mode 100644 index 00000000..e28ee5e6 --- /dev/null +++ b/dist/es-modules/core/contentstackError.js @@ -0,0 +1,43 @@ +export default function error(errorResponse) { + var config = errorResponse.config; + var response = errorResponse.response; + + if (!config || !response) { + throw errorResponse; + } + + var data = response.data; + var errorDetails = { + status: response.status, + statusText: response.statusText + }; + + if (config.headers && config.headers.authtoken) { + var token = "...".concat(config.headers.authtoken.substr(-5)); + config.headers.authtoken = token; + } + + if (config.headers && config.headers.authorization) { + var _token = "...".concat(config.headers.authorization.substr(-5)); + + config.headers.authorization = _token; + } + + errorDetails.request = { + url: config.url, + method: config.method, + data: config.data, + headers: config.headers + }; + + if (data) { + errorDetails.errorMessage = data.error_message || ''; + errorDetails.errorCode = data.error_code || 0; + errorDetails.errors = data.errors || {}; + } + + var error = new Error(); + Object.assign(error, errorDetails); + error.message = JSON.stringify(errorDetails); + throw error; +} \ No newline at end of file diff --git a/dist/es-modules/core/contentstackHTTPClient.js b/dist/es-modules/core/contentstackHTTPClient.js new file mode 100644 index 00000000..832d7227 --- /dev/null +++ b/dist/es-modules/core/contentstackHTTPClient.js @@ -0,0 +1,101 @@ +import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; +import _defineProperty from "@babel/runtime/helpers/defineProperty"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import clonedeep from 'lodash/cloneDeep'; +import Qs from 'qs'; +import axios from 'axios'; +import contentstackRetry from './contentstack-retry'; +import { isHost } from './Util'; +export default function contentstackHttpClient(options) { + var defaultConfig = { + insecure: false, + retryOnError: true, + logHandler: function logHandler(level, data) { + if (level === 'error' && data) { + var title = [data.name, data.message].filter(function (a) { + return a; + }).join(' - '); + console.error("[error] ".concat(title)); + return; + } + + console.log("[".concat(level, "] ").concat(data)); + }, + retryCondition: function retryCondition(error) { + if (error.response && error.response.status === 429) { + return true; + } + + return false; + }, + headers: {}, + basePath: '', + proxy: false, + httpAgent: false, + httpsAgent: false, + adapter: false, + timeout: 30000 + }; + + var config = _objectSpread(_objectSpread({}, defaultConfig), clonedeep(options)); + + if (config.apiKey) { + config.headers['apiKey'] = config.apiKey; + } + + if (config.accessToken) { + config.headers['accessToken'] = config.accessToken; + } + + var protocol = config.insecure ? 'http' : 'https'; + var hostname = config.defaultHostName; + var port = config.port || 443; + var version = config.version || 'v3'; + + if (isHost(config.host)) { + var parsed = config.host.split(':'); + + if (parsed.length === 2) { + var _parsed = _slicedToArray(parsed, 2); + + hostname = _parsed[0]; + port = _parsed[1]; + } else { + hostname = parsed[0]; + } + } + + if (config.basePath) { + config.basePath = "/".concat(config.basePath.split('/').filter(Boolean).join('/')); + } + + var baseURL = config.endpoint || "".concat(protocol, "://").concat(hostname, ":").concat(port).concat(config.basePath, "/").concat(version); + + var axiosOptions = _objectSpread(_objectSpread({ + // Axios + baseURL: baseURL + }, config), {}, { + paramsSerializer: function paramsSerializer(params) { + var query = params.query; + delete params.query; + var qs = Qs.stringify(params, { + arrayFormat: 'brackets' + }); + + if (query) { + qs = qs + "&query=".concat(encodeURI(JSON.stringify(query))); + } + + return qs; + } + }); + + var instance = axios.create(axiosOptions); + instance.httpClientParams = options; + contentstackRetry(instance, axiosOptions, config.retyLimit, config.retryDelay); + return instance; +} \ No newline at end of file diff --git a/dist/es-modules/entity.js b/dist/es-modules/entity.js new file mode 100644 index 00000000..10199945 --- /dev/null +++ b/dist/es-modules/entity.js @@ -0,0 +1,457 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _defineProperty from "@babel/runtime/helpers/defineProperty"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import error from './core/contentstackError'; +import cloneDeep from 'lodash/cloneDeep'; +import Query from './query/index'; +export var publish = function publish(http, type) { + return /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) { + var publishDetails, _ref$locale, locale, _ref$version, version, _ref$scheduledAt, scheduledAt, url, headers, httpBody; + + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + publishDetails = _ref.publishDetails, _ref$locale = _ref.locale, locale = _ref$locale === void 0 ? null : _ref$locale, _ref$version = _ref.version, version = _ref$version === void 0 ? null : _ref$version, _ref$scheduledAt = _ref.scheduledAt, scheduledAt = _ref$scheduledAt === void 0 ? null : _ref$scheduledAt; + url = this.urlPath + '/publish'; + headers = { + headers: _objectSpread({}, cloneDeep(this.stackHeaders)) + } || {}; + httpBody = {}; + httpBody[type] = cloneDeep(publishDetails); + return _context.abrupt("return", publishUnpublish(http, url, httpBody, headers, locale, version, scheduledAt)); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref2.apply(this, arguments); + }; + }(); +}; +export var unpublish = function unpublish(http, type) { + return /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3) { + var publishDetails, _ref3$locale, locale, _ref3$version, version, _ref3$scheduledAt, scheduledAt, url, headers, httpBody; + + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + publishDetails = _ref3.publishDetails, _ref3$locale = _ref3.locale, locale = _ref3$locale === void 0 ? null : _ref3$locale, _ref3$version = _ref3.version, version = _ref3$version === void 0 ? null : _ref3$version, _ref3$scheduledAt = _ref3.scheduledAt, scheduledAt = _ref3$scheduledAt === void 0 ? null : _ref3$scheduledAt; + url = this.urlPath + '/unpublish'; + headers = { + headers: _objectSpread({}, cloneDeep(this.stackHeaders)) + } || {}; + httpBody = {}; + httpBody[type] = cloneDeep(publishDetails); + return _context2.abrupt("return", publishUnpublish(http, url, httpBody, headers, locale, version, scheduledAt)); + + case 6: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function (_x2) { + return _ref4.apply(this, arguments); + }; + }(); +}; +export var publishUnpublish = /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(http, url, httpBody, headers) { + var locale, + version, + scheduledAt, + response, + _args3 = arguments; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + locale = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : null; + version = _args3.length > 5 && _args3[5] !== undefined ? _args3[5] : null; + scheduledAt = _args3.length > 6 && _args3[6] !== undefined ? _args3[6] : null; + + if (locale !== null) { + httpBody.locale = locale; + } + + if (version !== null) { + httpBody.version = version; + } + + if (scheduledAt !== null) { + httpBody.scheduled_at = scheduledAt; + } + + _context3.prev = 6; + _context3.next = 9; + return http.post(url, httpBody, headers); + + case 9: + response = _context3.sent; + + if (!response.data) { + _context3.next = 14; + break; + } + + return _context3.abrupt("return", response.data); + + case 14: + throw error(response); + + case 15: + _context3.next = 20; + break; + + case 17: + _context3.prev = 17; + _context3.t0 = _context3["catch"](6); + throw error(_context3.t0); + + case 20: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[6, 17]]); + })); + + return function publishUnpublish(_x3, _x4, _x5, _x6) { + return _ref5.apply(this, arguments); + }; +}(); +export var upload = /*#__PURE__*/function () { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref6) { + var http, urlPath, stackHeaders, formData, params, _ref6$method, method, headers; + + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + http = _ref6.http, urlPath = _ref6.urlPath, stackHeaders = _ref6.stackHeaders, formData = _ref6.formData, params = _ref6.params, _ref6$method = _ref6.method, method = _ref6$method === void 0 ? 'POST' : _ref6$method; + headers = { + headers: _objectSpread(_objectSpread(_objectSpread({}, params), formData.getHeaders()), cloneDeep(stackHeaders)) + } || {}; + + if (!(method === 'POST')) { + _context4.next = 6; + break; + } + + return _context4.abrupt("return", http.post(urlPath, formData, headers)); + + case 6: + return _context4.abrupt("return", http.put(urlPath, formData, headers)); + + case 7: + case "end": + return _context4.stop(); + } + } + }, _callee4); + })); + + return function upload(_x7) { + return _ref7.apply(this, arguments); + }; +}(); +export var create = function create(_ref8) { + var http = _ref8.http, + params = _ref8.params; + return /*#__PURE__*/function () { + var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(data, param) { + var headers, response; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + headers = { + headers: _objectSpread(_objectSpread({}, cloneDeep(params)), cloneDeep(this.stackHeaders)), + params: _objectSpread({}, cloneDeep(param)) + } || {}; + _context5.prev = 1; + _context5.next = 4; + return http.post(this.urlPath, data, headers); + + case 4: + response = _context5.sent; + + if (!response.data) { + _context5.next = 9; + break; + } + + return _context5.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 9: + throw error(response); + + case 10: + _context5.next = 15; + break; + + case 12: + _context5.prev = 12; + _context5.t0 = _context5["catch"](1); + throw error(_context5.t0); + + case 15: + case "end": + return _context5.stop(); + } + } + }, _callee5, this, [[1, 12]]); + })); + + return function (_x8, _x9) { + return _ref9.apply(this, arguments); + }; + }(); +}; +export var exportObject = function exportObject(_ref10) { + var http = _ref10.http; + return /*#__PURE__*/function () { + var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(param) { + var headers, response; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + headers = { + params: _objectSpread({}, cloneDeep(param)), + headers: _objectSpread({}, cloneDeep(this.stackHeaders)) + } || {}; + _context6.prev = 1; + _context6.next = 4; + return http.get(this.urlPath, headers); + + case 4: + response = _context6.sent; + + if (!response.data) { + _context6.next = 9; + break; + } + + return _context6.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 9: + throw error(response); + + case 10: + _context6.next = 15; + break; + + case 12: + _context6.prev = 12; + _context6.t0 = _context6["catch"](1); + throw error(_context6.t0); + + case 15: + case "end": + return _context6.stop(); + } + } + }, _callee6, this, [[1, 12]]); + })); + + return function (_x10) { + return _ref11.apply(this, arguments); + }; + }(); +}; +export var query = function query(_ref12) { + var http = _ref12.http, + wrapperCollection = _ref12.wrapperCollection; + return function () { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (this.organization_uid) { + params.query['org_uid'] = this.organization_uid; + } + + return Query(http, this.urlPath, params, this.stackHeaders, wrapperCollection); + }; +}; +export var update = function update(http, type) { + return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { + var param, + updateData, + response, + _args7 = arguments; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + param = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}; + updateData = {}; + updateData[type] = cloneDeep(this); + _context7.prev = 3; + _context7.next = 6; + return http.put(this.urlPath, updateData, { + headers: _objectSpread({}, cloneDeep(this.stackHeaders)), + params: _objectSpread({}, cloneDeep(param)) + }); + + case 6: + response = _context7.sent; + + if (!response.data) { + _context7.next = 11; + break; + } + + return _context7.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders, this.contentType_uid))); + + case 11: + throw error(response); + + case 12: + _context7.next = 17; + break; + + case 14: + _context7.prev = 14; + _context7.t0 = _context7["catch"](3); + throw error(_context7.t0); + + case 17: + case "end": + return _context7.stop(); + } + } + }, _callee7, this, [[3, 14]]); + })); +}; +export var deleteEntity = function deleteEntity(http) { + return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { + var param, + headers, + response, + _args8 = arguments; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + param = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {}; + _context8.prev = 1; + headers = { + headers: _objectSpread({}, cloneDeep(this.stackHeaders)), + params: _objectSpread({}, cloneDeep(param)) + } || {}; + _context8.next = 5; + return http["delete"](this.urlPath, headers); + + case 5: + response = _context8.sent; + + if (!response.data) { + _context8.next = 10; + break; + } + + return _context8.abrupt("return", response.data); + + case 10: + throw error(response); + + case 11: + _context8.next = 16; + break; + + case 13: + _context8.prev = 13; + _context8.t0 = _context8["catch"](1); + throw error(_context8.t0); + + case 16: + case "end": + return _context8.stop(); + } + } + }, _callee8, this, [[1, 13]]); + })); +}; +export var fetch = function fetch(http, type) { + return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() { + var param, + headers, + response, + _args9 = arguments; + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + param = _args9.length > 0 && _args9[0] !== undefined ? _args9[0] : {}; + _context9.prev = 1; + headers = { + headers: _objectSpread({}, cloneDeep(this.stackHeaders)), + params: _objectSpread({}, cloneDeep(param)) + } || {}; + _context9.next = 5; + return http.get(this.urlPath, headers); + + case 5: + response = _context9.sent; + + if (!response.data) { + _context9.next = 11; + break; + } + + if (type === 'entry') { + response.data[type]['content_type'] = response.data['content_type']; + response.data[type]['schema'] = response.data['schema']; + } + + return _context9.abrupt("return", Object.assign(this, cloneDeep(response.data[type]))); + + case 11: + throw error(response); + + case 12: + _context9.next = 17; + break; + + case 14: + _context9.prev = 14; + _context9.t0 = _context9["catch"](1); + throw error(_context9.t0); + + case 17: + case "end": + return _context9.stop(); + } + } + }, _callee9, this, [[1, 14]]); + })); +}; +export function parseData(response, stackHeaders, contentTypeUID) { + var data = response.data || {}; + + if (stackHeaders) { + data.stackHeaders = stackHeaders; + } + + if (contentTypeUID) { + data.content_type = contentTypeUID; + } + + return data; +} \ No newline at end of file diff --git a/dist/es-modules/organization/index.js b/dist/es-modules/organization/index.js new file mode 100644 index 00000000..40d9e47e --- /dev/null +++ b/dist/es-modules/organization/index.js @@ -0,0 +1,508 @@ +import _defineProperty from "@babel/runtime/helpers/defineProperty"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import cloneDeep from 'lodash/cloneDeep'; +import error from '../core/contentstackError'; +import { fetch } from '../entity'; +import ContentstackCollection from '../contentstackCollection'; +import { RoleCollection } from '../stack/roles/index'; +import { StackCollection } from '../stack/index'; +import { UserCollection } from '../user'; +/** + * Organization is the top-level entity in the hierarchy of Contentstack, consisting of stacks and stack resources, and users. Organization allows easy management of projects as well as users within the Organization. Read more about Organizations.. + * @namespace Organization + */ + +export function Organization(http, data) { + var _this = this; + + this.urlPath = '/organizations'; + + if (data && data.organization) { + Object.assign(this, cloneDeep(data.organization)); + this.urlPath = "/organizations/".concat(this.uid); + /** + * @description The fetch Organization call fetches Organization details. + * @memberof Organization + * @func fetch + * @param {Int} include_plan The include_plan parameter includes the details of the plan that the organization has subscribed to. + * @returns {Promise} Promise for Organization instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').fetch() + * .then((organization) => console.log(organization)) + * + */ + + this.fetch = fetch(http, 'organization'); + + if (this.org_roles && this.org_roles.filter(function (role) { + return role.admin === true; + }).length > 0) { + /** + * @description The Get all stacks in an organization call fetches the list of all stacks in an Organization. + * @memberof Organization + * @func stacks + * @param {Int} limit The limit parameter will return a specific number of roles in the output. + * @param {Int} skip The skip parameter will skip a specific number of roles in the output. + * @param {String} asc When fetching roles, you can sort them in the ascending order with respect to the value of a specific field in the response body. + * @param {String} desc When fetching roles, you can sort them in the decending order with respect to the value of a specific field in the response body. + * @param {Boolean} include_count To retrieve the count of stack. + * @param {String} typeahead The type head contains value to be included in search. + * @returns {ContentstackCollection} Instance of ContentstackCollection. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').stacks({ include_count: true }) + * .then((collection) => console.log(collection)) + * + */ + this.stacks = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(param) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return http.get("".concat(_this.urlPath, "/stacks"), { + params: param + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new ContentstackCollection(response, http, null, StackCollection)); + + case 8: + return _context.abrupt("return", error(response)); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + return _context.abrupt("return", error(_context.t0)); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 11]]); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + /** + * @description The Transfer organization ownership call transfers the ownership of an Organization to another user. + * @memberof Organization + * @func transferOwnership + * @param {String} email The email address of the user to whom you wish to transfer the ownership of the organization. + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).transferOwnership('emailId') + * .then((response) => console.log(response.notice)) + * + */ + + + this.transferOwnership = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(email) { + var response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return http.post("".concat(_this.urlPath, "/transfer_ownership"), { + transfer_to: email + }); + + case 3: + response = _context2.sent; + + if (!response.data) { + _context2.next = 8; + break; + } + + return _context2.abrupt("return", response.data); + + case 8: + return _context2.abrupt("return", error(response)); + + case 9: + _context2.next = 14; + break; + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](0); + return _context2.abrupt("return", error(_context2.t0)); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[0, 11]]); + })); + + return function (_x2) { + return _ref2.apply(this, arguments); + }; + }(); + /** + * @description The Add users to organization call allows you to send invitations to add users to your organization. Only the owner or the admin of the organization can add users. + * @memberof Organization + * @func addUser + * @returns {ContentstackCollection} ContentstackCollection of instance. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').addUser({ users: { 'abc@test.com': ['org_uid1', 'org_uid2' ]}, stacks: { 'abc@test.com': { 'api_key1': [ 'stack_role_id' ] } } }) + * .then((response) => console.log(response)) + * + */ + + + this.addUser = /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(data) { + var response; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return http.post("".concat(_this.urlPath, "/share"), { + share: _objectSpread({}, data) + }); + + case 3: + response = _context3.sent; + + if (!response.data) { + _context3.next = 8; + break; + } + + return _context3.abrupt("return", new ContentstackCollection(response, http, null, UserCollection)); + + case 8: + return _context3.abrupt("return", error(response)); + + case 9: + _context3.next = 14; + break; + + case 11: + _context3.prev = 11; + _context3.t0 = _context3["catch"](0); + return _context3.abrupt("return", error(_context3.t0)); + + case 14: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[0, 11]]); + })); + + return function (_x3) { + return _ref3.apply(this, arguments); + }; + }(); + /** + * @description The Get all organization invitations call gives you a list of all the Organization invitations. + * @memberof Organization + * @func getInvitations + * @returns {String} Success message of invitation send. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').getInvitations() + * .then((response) => console.log(response.notice)) + * + */ + + + this.getInvitations = /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(param) { + var response; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.prev = 0; + _context4.next = 3; + return http.get("".concat(_this.urlPath, "/share"), { + params: param + }); + + case 3: + response = _context4.sent; + + if (!response.data) { + _context4.next = 8; + break; + } + + return _context4.abrupt("return", new ContentstackCollection(response, http, null, UserCollection)); + + case 8: + return _context4.abrupt("return", error(response)); + + case 9: + _context4.next = 14; + break; + + case 11: + _context4.prev = 11; + _context4.t0 = _context4["catch"](0); + return _context4.abrupt("return", error(_context4.t0)); + + case 14: + case "end": + return _context4.stop(); + } + } + }, _callee4, null, [[0, 11]]); + })); + + return function (_x4) { + return _ref4.apply(this, arguments); + }; + }(); + /** + * @description The Resend pending organization invitation call allows you to resend Organization invitations to users who have not yet accepted the earlier invitation. + * @memberof Organization + * @func resendInvitition + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').resendInvitition('invitation_uid') + * .then((response) => console.log(response.notice)) + * + */ + + + this.resendInvitation = /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(invitationUid) { + var response; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.prev = 0; + _context5.next = 3; + return http.get("".concat(_this.urlPath, "/").concat(invitationUid, "/resend_invitation")); + + case 3: + response = _context5.sent; + + if (!response.data) { + _context5.next = 8; + break; + } + + return _context5.abrupt("return", response.data); + + case 8: + return _context5.abrupt("return", error(response)); + + case 9: + _context5.next = 14; + break; + + case 11: + _context5.prev = 11; + _context5.t0 = _context5["catch"](0); + return _context5.abrupt("return", error(_context5.t0)); + + case 14: + case "end": + return _context5.stop(); + } + } + }, _callee5, null, [[0, 11]]); + })); + + return function (_x5) { + return _ref5.apply(this, arguments); + }; + }(); + /** + * @description A role is a collection of permissions that will be applicable to all the users who are assigned this role. + * @memberof Organization + * @func roles + * @param {Int} limit The limit parameter will return a specific number of roles in the output. + * @param {Int} skip The skip parameter will skip a specific number of roles in the output. + * @param {String} asc When fetching roles, you can sort them in the ascending order with respect to the value of a specific field in the response body. + * @param {String} desc When fetching roles, you can sort them in the decending order with respect to the value of a specific field in the response body. + * @param {Boolean}include_count To retrieve the count of roles. + * @param {Boolean} include_stack_roles The Include stack roles will return stack details in roles. + * @returns {Array} Array of Role instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('organization_uid').roles() + * .then((roles) => console.log(roles)) + * + */ + + + this.roles = /*#__PURE__*/function () { + var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(param) { + var response; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.prev = 0; + _context6.next = 3; + return http.get("".concat(_this.urlPath, "/roles"), { + params: param + }); + + case 3: + response = _context6.sent; + + if (!response.data) { + _context6.next = 8; + break; + } + + return _context6.abrupt("return", new ContentstackCollection(response, http, null, RoleCollection)); + + case 8: + return _context6.abrupt("return", error(response)); + + case 9: + _context6.next = 14; + break; + + case 11: + _context6.prev = 11; + _context6.t0 = _context6["catch"](0); + return _context6.abrupt("return", error(_context6.t0)); + + case 14: + case "end": + return _context6.stop(); + } + } + }, _callee6, null, [[0, 11]]); + })); + + return function (_x6) { + return _ref6.apply(this, arguments); + }; + }(); + } + } else { + /** + * @description The Get all organizations call lists all organizations related to the system user in the order that they were created. + * @memberof Organization + * @func fetchAll + * @param {Int} limit The limit parameter will return a specific number of roles in the output. + * @param {Int} skip The skip parameter will skip a specific number of roles in the output. + * @param {String} asc When fetching roles, you can sort them in the ascending order with respect to the value of a specific field in the response body. + * @param {String} desc When fetching roles, you can sort them in the decending order with respect to the value of a specific field in the response body. + * @param {Boolean}include_count To retrieve the count of roles. + * @param {String} typeahead The type head contains value to be included in search. + * @returns {ContentstackCollection} Result collection of content of specified module. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization().fetchAll() + * .then((collection) => console.log(collection)) + * + */ + this.fetchAll = /*#__PURE__*/function () { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(parmas) { + var response; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.prev = 0; + _context7.next = 3; + return http.get(_this.urlPath, { + params: parmas + }); + + case 3: + response = _context7.sent; + + if (!response.data) { + _context7.next = 8; + break; + } + + return _context7.abrupt("return", new ContentstackCollection(response, http, null, OrganizationCollection)); + + case 8: + throw error(response); + + case 9: + _context7.next = 14; + break; + + case 11: + _context7.prev = 11; + _context7.t0 = _context7["catch"](0); + throw error(_context7.t0); + + case 14: + case "end": + return _context7.stop(); + } + } + }, _callee7, null, [[0, 11]]); + })); + + return function (_x7) { + return _ref7.apply(this, arguments); + }; + }(); + } +} +export function OrganizationCollection(http, data) { + var obj = cloneDeep(data.organizations || []); + var organizationCollection = obj.map(function (userdata) { + return new Organization(http, { + organization: userdata + }); + }); + return organizationCollection; +} \ No newline at end of file diff --git a/dist/es-modules/query/index.js b/dist/es-modules/query/index.js new file mode 100644 index 00000000..e3acfc9e --- /dev/null +++ b/dist/es-modules/query/index.js @@ -0,0 +1,230 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _defineProperty from "@babel/runtime/helpers/defineProperty"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import error from '../core/contentstackError'; +import cloneDeep from 'lodash/cloneDeep'; +import ContentstackCollection from '../contentstackCollection'; +export default function Query(http, urlPath, param) { + var stackHeaders = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var wrapperCollection = arguments.length > 4 ? arguments[4] : undefined; + var headers = {}; + + if (stackHeaders) { + headers.headers = stackHeaders; + } + + if (param) { + headers.params = _objectSpread({}, cloneDeep(param)); + } + /** + * @description This method will fetch content of query on specified module. + * @returns {ContentstackCollection} Result collection of content of specified module. + * @example All Stack + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query().find() + * .then((collection) => console.log(collection)) + * + * @example Query on stack + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query( { query: { name: 'Stack name' } }).find() + * .then((collection) => console.log(collection)) + * + */ + + + var find = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return http.get(urlPath, headers); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new ContentstackCollection(response, http, stackHeaders, wrapperCollection)); + + case 8: + throw error(response); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + throw error(_context.t0); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 11]]); + })); + + return function find() { + return _ref.apply(this, arguments); + }; + }(); + /** + * @description This method will fetch count of content for query on specified module. + * @returns {Object} Result is Object of content of specified module. + * @example All Stack + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query().count() + * .then((response) => console.log(response)) + * + * @example Query on Asset + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).query({ query: { title: 'Stack name' } }).count() + * .then((response) => console.log(response)) + * + */ + + + var count = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + headers.params = _objectSpread(_objectSpread({}, headers.params), {}, { + count: true + }); + _context2.prev = 1; + _context2.next = 4; + return http.get(urlPath, headers); + + case 4: + response = _context2.sent; + + if (!response.data) { + _context2.next = 9; + break; + } + + return _context2.abrupt("return", response.data); + + case 9: + throw error(response); + + case 10: + _context2.next = 15; + break; + + case 12: + _context2.prev = 12; + _context2.t0 = _context2["catch"](1); + throw error(_context2.t0); + + case 15: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[1, 12]]); + })); + + return function count() { + return _ref2.apply(this, arguments); + }; + }(); + /** + * @description This method will fetch content of query on specified module. + * @returns {ContentstackCollection} Result content of specified module. + * @example Stack + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query().findOne() + * .then((collection) => console.log(collection)) + * + * @example Query on stack + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query({ query: { title: 'Stack name' } }).findOne() + * .then((collection) => console.log(collection)) + * + */ + + + var findOne = /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var limitHeader, response; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + limitHeader = headers; + limitHeader.params.limit = 1; + _context3.prev = 2; + _context3.next = 5; + return http.get(urlPath, limitHeader); + + case 5: + response = _context3.sent; + + if (!response.data) { + _context3.next = 10; + break; + } + + return _context3.abrupt("return", new ContentstackCollection(response, http, stackHeaders, wrapperCollection)); + + case 10: + throw error(response); + + case 11: + _context3.next = 16; + break; + + case 13: + _context3.prev = 13; + _context3.t0 = _context3["catch"](2); + throw error(_context3.t0); + + case 16: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[2, 13]]); + })); + + return function findOne() { + return _ref3.apply(this, arguments); + }; + }(); + + return { + count: count, + find: find, + findOne: findOne + }; +} \ No newline at end of file diff --git a/dist/es-modules/stack/asset/folders/index.js b/dist/es-modules/stack/asset/folders/index.js new file mode 100644 index 00000000..4be99d93 --- /dev/null +++ b/dist/es-modules/stack/asset/folders/index.js @@ -0,0 +1,96 @@ +import cloneDeep from 'lodash/cloneDeep'; +import { update, deleteEntity, fetch, create } from '../../../entity'; +/** + * Folders refer to Asset Folders. + * @namespace Folder + */ + +export function Folder(http) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (data.stackHeaders) { + this.stackHeaders = data.stackHeaders; + } + + this.urlPath = "/assets/folders"; + + if (data.asset) { + Object.assign(this, cloneDeep(data.asset)); + this.urlPath = "/assets/folders/".concat(this.uid); + /** + * @description The Update Folder call lets you update the name and description of an existing Folder. + * @memberof Folder + * @func update + * @returns {Promise} Promise for Folder instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset().folder('uid').fetch() + * .then((folder) => { + * folder.name = 'My New folder' + * return folder.update() + * }) + * .then((folder) => console.log(folder)) + * + */ + + this.update = update(http, 'asset'); + /** + * @description The Delete folder call will delete an existing folder from the stack. + * @memberof Folder + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset().folder('uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch an asset call returns comprehensive information about a specific version of an asset of a stack. + * @memberof Folder + * @func fetch + * @returns {Promise} Promise for Folder instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset().folder('uid').fetch() + * .then((folder) => console.log(folder)) + * + */ + + this.fetch = fetch(http, 'asset'); + } else { + /** + * @description The Create a folder into the assets. + * @memberof Folder + * @func create + * @returns {Promise} Promise for Folder instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const asset = {name: 'My New contentType'} + * client.stack().asset().folders().create({ asset }) + * .then((folder) => console.log(folder)) + */ + this.create = create({ + http: http + }); + } +} +export function FolderCollection(http, data) { + var obj = cloneDeep(data.assets) || []; + var assetCollection = obj.map(function (userdata) { + return new Folder(http, { + asset: userdata, + stackHeaders: data.stackHeaders + }); + }); + return assetCollection; +} \ No newline at end of file diff --git a/dist/es-modules/stack/asset/index.js b/dist/es-modules/stack/asset/index.js new file mode 100644 index 00000000..1457600b --- /dev/null +++ b/dist/es-modules/stack/asset/index.js @@ -0,0 +1,353 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import cloneDeep from 'lodash/cloneDeep'; +import { update, deleteEntity, fetch, query, parseData, upload, publish, unpublish } from '../../entity'; +import { Folder } from './folders'; +import error from '../../core/contentstackError'; +import FormData from 'form-data'; +import { createReadStream } from 'fs'; +/** + * Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded in your Contentstack repository for future use. + * These files can be attached and used in multiple entries. Read more about Assets. + * @namespace Asset + */ + +export function Asset(http) { + var _this = this; + + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/assets"; + + if (data.asset) { + Object.assign(this, cloneDeep(data.asset)); + this.urlPath = "/assets/".concat(this.uid); + /** + * @description The Update Asset call lets you update the name and description of an existing Asset. + * @memberof Asset + * @func update + * @returns {Promise} Promise for Asset instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset('uid').fetch() + * .then((asset) => { + * asset.title = 'My New asset' + * asset.description = 'Asset description' + * return asset.update() + * }) + * .then((asset) => console.log(asset)) + * + */ + + this.update = update(http, 'asset'); + /** + * @description The Delete asset call will delete an existing asset from the stack. + * @memberof Asset + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset('uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch an asset call returns comprehensive information about a specific version of an asset of a stack. + * @memberof Asset + * @func fetch + * @returns {Promise} Promise for Asset instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset('uid').fetch() + * .then((asset) => console.log(asset)) + * + */ + + this.fetch = fetch(http, 'asset'); + /** + * @description The Replace asset call will replace an existing asset with another file on the stack. + * @memberof Asset + * @func replace + * @returns {Promise} Promise for Asset instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const asset = { + * upload: 'path/to/file.png', + * } + * + * client.stack({ api_key: 'api_key'}).asset('uid').replace(asset) + * .then((asset) => console.log(asset)) + * + */ + + this.replace = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(data, params) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return upload({ + http: http, + urlPath: this.urlPath, + stackHeaders: this.stackHeaders, + formData: createFormData(data), + params: params, + method: 'PUT' + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 8: + throw error(response); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + throw error(_context.t0); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[0, 11]]); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + /** + * @description The Publish an asset call is used to publish a specific version of an asset on the desired environment either immediately or at a later date/time. + * @memberof Asset + * @func publish + * @returns {Promise} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const asset = { + * "locales": [ + * "en-us" + * ], + * "environments": [ + * "development" + * ] + * } + * + * client.stack({ api_key: 'api_key'}).asset('uid').publish({ publishDetails: asset, version: 1, scheduledAt: "2019-02-08T18:30:00.000Z"}) + * .then((response) => console.log(response.notice)) + * + */ + + + this.publish = publish(http, 'asset'); + /** + * @description The Replace asset call will replace an existing asset with another file on the stack. + * @memberof Asset + * @func unpublish + * @returns {Promise} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const asset = { + * "locales": [ + * "en-us" + * ], + * "environments": [ + * "development" + * ] + * } + * + * client.stack({ api_key: 'api_key'}).asset('uid').unpublish({ publishDetails: asset, version: 1, scheduledAt: "2019-02-08T18:30:00.000Z"}) + * .then((response) => console.log(response.notice)) + * + */ + + this.unpublish = unpublish(http, 'asset'); + } else { + /** + * @description The Folder allows to fetch and create folders in assets. + * @memberof Asset + * @func folder + * @returns {Promise} Promise for Entry instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const asset = {name: 'My New contentType'} + * client.stack({ api_key: 'api_key'}).asset('uid').folder().create({ asset }) + * .then((folder) => console.log(folder)) + */ + this.folder = function () { + var folderUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (folderUid) { + data.asset = { + uid: folderUid + }; + } + + return new Folder(http, data); + }; + /** + * @description The Create an asset call creates a new asset. + * @memberof Asset + * @func create + * @returns {Promise} Promise for Asset instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const asset = { + * upload: 'path/to/file.png', + * title: 'Title', + * description: 'Desc' + * } + * + * client.stack({ api_key: 'api_key'}).asset().create(asset) + * .then((asset) => console.log(asset)) + */ + + + this.create = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(data, params) { + var response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return upload({ + http: http, + urlPath: this.urlPath, + stackHeaders: this.stackHeaders, + formData: createFormData(data), + params: params + }); + + case 3: + response = _context2.sent; + + if (!response.data) { + _context2.next = 8; + break; + } + + return _context2.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 8: + throw error(response); + + case 9: + _context2.next = 14; + break; + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](0); + throw error(_context2.t0); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, this, [[0, 11]]); + })); + + return function (_x3, _x4) { + return _ref2.apply(this, arguments); + }; + }(); + /** + * @description The Query on Asset will allow to fetch details of all or specific Asset. + * @memberof Asset + * @param {Object} params - URI parameters + * @prop {Object} params.query - Queries that you can use to fetch filtered results. + * @func query + * @returns {Array} Array of Asset. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().asset().query({ query: { filename: 'Asset Name' } }).find() + * .then((asset) => console.log(asset)) + */ + + + this.query = query({ + http: http, + wrapperCollection: AssetCollection + }); + } + + return this; +} +export function AssetCollection(http, data) { + var obj = cloneDeep(data.assets) || []; + var assetCollection = obj.map(function (userdata) { + return new Asset(http, { + asset: userdata, + stackHeaders: data.stackHeaders + }); + }); + return assetCollection; +} + +function createFormData(data) { + var formData = new FormData(); + + if (typeof data['parent_uid'] === 'string') { + formData.append('asset[parent_uid]', data['parent_uid']); + } + + if (typeof data.description === 'string') { + formData.append('asset[description]', data.description); + } + + if (data.tags instanceof Array) { + formData.append('asset[tags]', data.tags.join(',')); + } else if (typeof data.tags === 'string') { + formData.append('asset[tags]', data.tags); + } + + if (typeof data.title === 'string') { + formData.append('asset[title]', data.title); + } + + var uploadStream = createReadStream(data.upload); + formData.append('asset[upload]', uploadStream); + return formData; +} \ No newline at end of file diff --git a/dist/es-modules/stack/bulkOperation/index.js b/dist/es-modules/stack/bulkOperation/index.js new file mode 100644 index 00000000..c65aef67 --- /dev/null +++ b/dist/es-modules/stack/bulkOperation/index.js @@ -0,0 +1,223 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _defineProperty from "@babel/runtime/helpers/defineProperty"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import cloneDeep from 'lodash/cloneDeep'; +import { publishUnpublish } from '../../entity'; +/** + * Bulk operations such as Publish, Unpublish, and Delete on multiple entries or assets. + * @namespace BulkOperation + */ + +export function BulkOperation(http) { + var _this = this; + + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/bulk"; + /** + * The Publish entries and assets in bulk request allows you to publish multiple entries and assets at the same time. + * @memberof BulkOperation + * @func publish + * @returns {Promise} Response Object. + * @param {Boolean} params.details - Set this with details containing 'entries', 'assets', 'locales', and 'environments' to which you want to publish the entries or assets. + * @param {Boolean} params.skip_workflow_stage_check Set this to 'true' to publish the entries that are at a workflow stage where they satisfy the applied publish rules. + * @param {Boolean} params.approvals Set this to 'true' to publish the entries that do not require an approval to be published. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const publishDetails = { + * entries: [ + * { + * uid: '{{entry_uid}}', + * content_type: '{{content_type_uid}}', + * version: '{{version}}', + * locale: '{{entry_locale}}' + * } + * ], + * assets: [{ + * uid: '{{uid}}' + * }], + * locales: [ + * 'en' + * ], + * environments: [ + * '{{env_name}}/env_uid}}' + * ] + * } + * client.stack({ api_key: 'api_key'}).publish({ details: publishDetails }) + * .then((response) => { console.log(response.notice) }) + * + */ + + this.publish = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var params, + httpBody, + headers, + _args = arguments; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + params = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + httpBody = {}; + + if (params.details) { + httpBody = cloneDeep(params.details); + } + + headers = { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }; + + if (params.skip_workflow_stage_check) { + headers.headers.skip_workflow_stage_check = params.skip_workflow_stage_check; + } + + if (params.approvals) { + headers.headers.approvals = params.approvals; + } + + return _context.abrupt("return", publishUnpublish(http, '/bulk/publish', httpBody, headers)); + + case 7: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + /** + * The Unpublish entries and assets in bulk request allows you to unpublish multiple entries and assets at the same time. + * @memberof BulkOperation + * @func unpublish + * @returns {Promise} Response Object. + * @param {Boolean} params.details - Set this with details containing 'entries', 'assets', 'locales', and 'environments' to which you want to unpublish the entries or assets. If you do not specify a source locale, the entries or assets will be unpublished in the master locale automatically. + * @param {Boolean} params.skip_workflow_stage_check Set this to 'true' to publish the entries that are at a workflow stage where they satisfy the applied publish rules. + * @param {Boolean} params.approvals Set this to 'true' to publish the entries that do not require an approval to be published. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const publishDetails = { + * entries: [ + * { + * uid: '{{entry_uid}}', + * content_type: '{{content_type_uid}}', + * version: '{{version}}', + * locale: '{{entry_locale}}' + * } + * ], + * assets: [{ + * uid: '{{uid}}' + * }], + * locales: [ + * 'en' + * ], + * environments: [ + * '{{env_name}}/env_uid}}' + * ] + * } + * client.stack({ api_key: 'api_key'}).unpublish({ details: publishDetails }) + * .then((response) => { console.log(response.notice) }) + * + */ + + this.unpublish = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var params, + httpBody, + headers, + _args2 = arguments; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + params = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}; + httpBody = {}; + + if (params.details) { + httpBody = cloneDeep(params.details); + } + + headers = { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }; + + if (params.skip_workflow_stage_check) { + headers.headers.skip_workflow_stage_check = params.skip_workflow_stage_check; + } + + if (params.approvals) { + headers.headers.approvals = params.approvals; + } + + return _context2.abrupt("return", publishUnpublish(http, '/bulk/unpublish', httpBody, headers)); + + case 7: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + /** + * The Delete entries and assets in bulk request allows you to delete multiple entries and assets at the same time. + * @memberof BulkOperation + * @func delete + * @returns {Promise} Success message + * @param {Boolean} params.details - Set this with details specifing the content type UIDs, entry UIDs or asset UIDs, and locales of which the entries or assets you want to delete. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const publishDetails = { + * entries: [ + * { + * uid: '{{entry_uid}}', + * content_type: '{{content_type_uid}}', + * locale: '{{entry_locale}}' + * } + * ], + * assets: [{ + * uid: '{{uid}}' + * }] + * } + * client.stack({ api_key: 'api_key'}).delete({ details: publishDetails }) + * .then((response) => { console.log(response.notice) }) + * + */ + + this["delete"] = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var params, + httpBody, + headers, + _args3 = arguments; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + params = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}; + httpBody = {}; + + if (params.details) { + httpBody = cloneDeep(params.details); + } + + headers = { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }; + return _context3.abrupt("return", publishUnpublish(http, '/bulk/delete', httpBody, headers)); + + case 5: + case "end": + return _context3.stop(); + } + } + }, _callee3); + })); +} \ No newline at end of file diff --git a/dist/es-modules/stack/contentType/entry/index.js b/dist/es-modules/stack/contentType/entry/index.js new file mode 100644 index 00000000..571252af --- /dev/null +++ b/dist/es-modules/stack/contentType/entry/index.js @@ -0,0 +1,281 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import cloneDeep from 'lodash/cloneDeep'; +import { create, update, deleteEntity, fetch, query, upload, parseData, publish, unpublish } from '../../../entity'; +import FormData from 'form-data'; +import { createReadStream } from 'fs'; +import error from '../../../core/contentstackError'; +/** + * An entry is the actual piece of content created using one of the defined content types. Read more about Entries. + * @namespace Entry + */ + +export function Entry(http, data) { + var _this = this; + + this.stackHeaders = data.stackHeaders; + this.content_type_uid = data.content_type_uid; + this.urlPath = "/content_types/".concat(this.content_type_uid, "/entries"); + + if (data && data.entry) { + Object.assign(this, cloneDeep(data.entry)); + this.urlPath = "/content_types/".concat(this.content_type_uid, "/entries/").concat(this.uid); + /** + * @description The Create an entry call creates a new entry for the selected content type. + * @memberof Entry + * @func update + * @param locale - Locale code to localized entry + * @returns {Promise} Promise for Entry instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').fetch() + * .then((entry) => { + * entry.title = 'My New Entry' + * entry.description = 'Entry description' + * return Entry.update() + * }) + * .then((entry) => console.log(entry)) + * + * @example + * // To Localize Entry pass locale in parameter + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').fetch() + * .then((entry) => { + * entry.title = 'My New Entry' + * entry.description = 'Entry description' + * return Entry.update({ locale: 'en-at' }) + * }) + * .then((entry) => console.log(entry)) + * + */ + + this.update = update(http, 'entry'); + /** + * @description The Delete an entry call is used to delete a specific entry from a content type. + * @memberof Entry + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch Entry call fetches Entry details. + * @memberof Entry + * @func fetch + * @param {Int} version Enter the version number of the entry that you want to retrieve. However, to retrieve a specific version of an entry, you need to keep the environment parameter blank. + * @param {Int} locale Enter the code of the language of which the entries need to be included. Only the entries published in this locale will be displayed. + * @param {Int} include_workflow Enter 'true' to include the workflow details of the entry. + * @param {Int} include_publish_details Enter 'true' to include the publish details of the entry. + * @returns {Promise} Promise for Entry instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').fetch() + * .then((entry) => console.log(entry)) + * + */ + + this.fetch = fetch(http, 'entry'); + /** + * @description The Publish an asset call is used to publish a specific version of an asset on the desired environment either immediately or at a later date/time. + * @memberof Entry + * @func publish + * @returns {Promise} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const entry = { + * "locales": [ + * "en-us" + * ], + * "environments": [ + * "development" + * ] + * } + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').publish({ publishDetails: entry, locale: "en-us", version: 1, scheduledAt: "2019-02-08T18:30:00.000Z"}) + * .then((response) => console.log(response.notice)) + * + */ + + this.publish = publish(http, 'entry'); + /** + * @description The Replace asset call will replace an existing asset with another file on the stack. + * @memberof Entry + * @func unpublish + * @returns {Promise} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const entry = { + * "locales": [ + * "en-us" + * ], + * "environments": [ + * "development" + * ] + * } + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry('uid').unpublish({ publishDetails: entry, locale: "en-us", version: 1, scheduledAt: "2019-02-08T18:30:00.000Z"}) + * .then((response) => console.log(response.notice)) + * + */ + + this.unpublish = unpublish(http, 'entry'); + } else { + /** + * @description The Create an entry call creates a new entry for the selected content type. + * @memberof Entry + * @func create + * @returns {Promise} Promise for Entry instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const entry = { + * title: 'Sample Entry', + * url: '/sampleEntry' + * } + * client.stack().contentType('content_type_uid').entry().create({ entry }) + * .then((entry) => console.log(entry)) + */ + this.create = create({ + http: http + }); + /** + * @description The Query on Entry will allow to fetch details of all or specific Entry + * @memberof Entry + * @func query + * @param {Int} locale Enter the code of the language of which the entries need to be included. Only the entries published in this locale will be displayed. + * @param {Int} include_workflow Enter 'true' to include the workflow details of the entry. + * @param {Int} include_publish_details Enter 'true' to include the publish details of the entry. + * @param {Object} query Queries that you can use to fetch filtered results. + * @returns {Array} Array of Entry. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().contentType('content_type_uid').entry().query({ query: { title: 'Entry title' } }).find() + * .then((entries) => console.log(entries)) + */ + + this.query = query({ + http: http, + wrapperCollection: EntryCollection + }); + } + /** + * @description The Import Entry calls given below help you to import entries by uploading JSON files. + * @memberof Entry + * @func import + * @param {String} entry Select the JSON file of the entry that you wish to import. + * @param {String} locale Enter the code of the language to import the entry of that particular language. + * @param {Boolean} overwrite Select 'true' to replace an existing entry with the imported entry file. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').entry() + * .import({ + * entry: 'path/to/file.json', + * overright: true + * }) + * .then((entry) => console.log(entry)) + * + */ + + + this["import"] = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) { + var entry, _ref$locale, locale, _ref$overwrite, overwrite, importUrl, response; + + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + entry = _ref.entry, _ref$locale = _ref.locale, locale = _ref$locale === void 0 ? null : _ref$locale, _ref$overwrite = _ref.overwrite, overwrite = _ref$overwrite === void 0 ? false : _ref$overwrite; + importUrl = "".concat(_this.urlPath, "/import?overwrite=").concat(overwrite); + + if (locale) { + importUrl = "".concat(importUrl, "&locale=").concat(locale); + } + + _context.prev = 3; + _context.next = 6; + return upload({ + http: http, + urlPath: importUrl, + stackHeaders: _this.stackHeaders, + formData: createFormData(entry) + }); + + case 6: + response = _context.sent; + + if (!response.data) { + _context.next = 11; + break; + } + + return _context.abrupt("return", new _this.constructor(http, parseData(response, _this.stackHeaders))); + + case 11: + throw error(response); + + case 12: + _context.next = 17; + break; + + case 14: + _context.prev = 14; + _context.t0 = _context["catch"](3); + throw error(_context.t0); + + case 17: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[3, 14]]); + })); + + return function (_x) { + return _ref2.apply(this, arguments); + }; + }(); + + return this; +} +export function EntryCollection(http, data) { + var obj = cloneDeep(data.entries) || []; + var entryCollection = obj.map(function (entry) { + return new Entry(http, { + entry: entry, + content_type_uid: 'uid', + stackHeaders: data.stackHeaders + }); + }); + return entryCollection; +} + +function createFormData(entry) { + var formData = new FormData(); + var uploadStream = createReadStream(entry); + formData.append('entry', uploadStream); + return formData; +} \ No newline at end of file diff --git a/dist/es-modules/stack/contentType/index.js b/dist/es-modules/stack/contentType/index.js new file mode 100644 index 00000000..51d01c6a --- /dev/null +++ b/dist/es-modules/stack/contentType/index.js @@ -0,0 +1,252 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +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 Content Types. + * @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. + * @memberof ContentType + * @func update + * @returns {Promise} 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 Delete ContentType call is used to delete an existing ContentType permanently from your Stack. + * @memberof ContentType + * @func delete + * @returns {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} Promise for ContentType instance + * @param {Int} version Enter the unique ID of the content type of which you want to retrieve the details. The UID is generated based on the title of the content type. The unique ID of a content type is unique across a stack. + * @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 Content type defines the structure or schema of a page or a section of your web or mobile property. + * @param {String} uid The UID of the ContentType you want to get details. + * @returns {ContenType} Instace of ContentType. + * @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((contentType) => console.log(contentType)) + */ + + this.entry = function () { + var uid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + data.content_type_uid = _this.uid; + + if (uid) { + data.entry = { + uid: uid + }; + } + + return new Entry(http, data); + }; + } 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} 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 to fetch details of all or specific Content Type + * @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 {Array} Array of ContentTyoe. + * + * @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 + * @param {String} data.content_type path to file + * @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) + * .then((contentType) => console.log(contentType)) + * + */ + + this["import"] = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(data) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return upload({ + http: http, + urlPath: "".concat(this.urlPath, "/import"), + stackHeaders: this.stackHeaders, + formData: createFormData(data) + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 8: + throw error(response); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + throw error(_context.t0); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[0, 11]]); + })); + + return function (_x) { + return _ref.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; +} + +function createFormData(data) { + var formData = new FormData(); + var uploadStream = createReadStream(data.content_type); + formData.append('content_type', uploadStream); + return formData; +} \ No newline at end of file diff --git a/dist/es-modules/stack/deliveryToken/index.js b/dist/es-modules/stack/deliveryToken/index.js new file mode 100644 index 00000000..f3274ea2 --- /dev/null +++ b/dist/es-modules/stack/deliveryToken/index.js @@ -0,0 +1,118 @@ +import cloneDeep from 'lodash/cloneDeep'; +import { create, update, deleteEntity, fetch, query } from '../../entity'; // import ContentstackCollection from '../../contentstackCollection' +// import error from '../../core/contentstackError' + +export function DeliveryToken(http) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/stacks/delivery_tokens"; + + if (data.token) { + Object.assign(this, cloneDeep(data.token)); + this.urlPath = "/stacks/delivery_tokens/".concat(this.uid); + /** + * @description The Update DeliveryToken call lets you update the name and description of an existing DeliveryToken. + * @memberof DeliveryToken + * @func update + * @returns {Promise} Promise for DeliveryToken instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).deliveryToken('delivery_token_uid').fetch() + * .then((deliveryToken) => { + * deliveryToken.title = 'My New Content Type' + * deliveryToken.description = 'Content Type description' + * return deliveryToken.update() + * }) + * .then((deliveryToken) => console.log(deliveryToken)) + * + */ + + this.update = update(http, 'token'); + /** + * @description The Delete DeliveryToken call is used to delete an existing DeliveryToken permanently from your Stack. + * @memberof DeliveryToken + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).deliveryToken('delivery_token_uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch DeliveryToken call fetches DeliveryToken details. + * @memberof DeliveryToken + * @func fetch + * @returns {Promise} Promise for DeliveryToken instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).deliveryToken('delivery_token_uid').fetch() + * .then((deliveryToken) => console.log(deliveryToken)) + * + */ + + this.fetch = fetch(http, 'token'); + } else { + /** + * @description The Create a DeliveryToken call creates a new deliveryToken in a particular stack of your Contentstack account. + * @memberof DeliveryToken + * @func create + * @returns {Promise} Promise for DeliveryToken instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const token = { + * name: 'Test', + * description: 'This is a demo token.', + * scope: [{ + * module: 'environment', + * environments: ['development'], + * acl: { + * read: true + * } + * }] + * } + * + * client.stack().deliveryToken().create({ token }) + * .then((deliveryToken) => console.log(deliveryToken)) + */ + this.create = create({ + http: http + }); + /** + * @description The ‘Get all deliveryToken’ request returns comprehensive information about all deliveryToken created in a stack. + * @memberof DeliveryToken + * @func query + * @returns {ContentstackCollection} Instance of ContentstackCollection. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().deliveryToken().query({ query: { name: 'token_name' } })).find() + * .then((contentstackCollection) => console.log(contentstackCollection)) + */ + + this.query = query({ + http: http, + wrapperCollection: DeliveryTokenCollection + }); + } +} +export function DeliveryTokenCollection(http, data) { + var obj = cloneDeep(data.tokens) || []; + var deliveryTokenCollection = obj.map(function (userdata) { + return new DeliveryToken(http, { + token: userdata, + stackHeaders: data.stackHeaders + }); + }); + return deliveryTokenCollection; +} \ No newline at end of file diff --git a/dist/es-modules/stack/environment/index.js b/dist/es-modules/stack/environment/index.js new file mode 100644 index 00000000..e268fb6a --- /dev/null +++ b/dist/es-modules/stack/environment/index.js @@ -0,0 +1,120 @@ +import cloneDeep from 'lodash/cloneDeep'; +import { create, update, deleteEntity, fetch, query } from '../../entity'; +export function Environment(http) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/environments"; + + if (data.environment) { + Object.assign(this, cloneDeep(data.environment)); + this.urlPath = "/environments/".concat(this.name); + /** + * @description The Update Environment call lets you update the name and description of an existing Environment. + * @memberof Environment + * @func update + * @returns {Promise} Promise for Environment instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).environment('uid').fetch() + * .then((environment) => { + * environment.title = 'My New Content Type' + * environment.description = 'Content Type description' + * return environment.update() + * }) + * .then((environment) => console.log(environment)) + * + */ + + this.update = update(http, 'environment'); + /** + * @description The Delete Environment call is used to delete an existing Environment permanently from your Stack. + * @memberof Environment + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).environment('uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch Environment call fetches Environment details. + * @memberof Environment + * @func fetch + * @returns {Promise} Promise for Environment instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).environment('uid').fetch() + * .then((environment) => console.log(environment)) + * + */ + + this.fetch = fetch(http, 'environment'); + } else { + /** + * @description The Create a Environment call creates a new environment in a particular stack of your Contentstack account. + * @memberof Environment + * @func create + * @returns {Promise} Promise for Environment instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const environment = { + * name: 'development', + * servers: [ + * { + * name: 'default' + * } + * ], + * urls: [ + * { + * locale: 'en-us', + * url: 'http://example.com/' + * } + * ], + * deploy_content: true + * } + * client.stack({ api_key: 'api_key'}).environment().create({ environment }) + * .then((environment) => console.log(environment)) + */ + this.create = create({ + http: http + }); + /** + * @description The Query on GlobalField will allow to fetch details of all or specific GlobalField + * @memberof Environment + * @func query + * @returns {Array} Array of GlobalField. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).environment().query({ query: { name: 'Environment Name' } }).find() + * .then((globalFields) => console.log(globalFields)) + */ + + this.query = query({ + http: http, + wrapperCollection: EnvironmentCollection + }); + } +} +export function EnvironmentCollection(http, data) { + var obj = cloneDeep(data.environments) || []; + var environmentCollection = obj.map(function (userdata) { + return new Environment(http, { + environment: userdata, + stackHeaders: data.stackHeaders + }); + }); + return environmentCollection; +} \ No newline at end of file diff --git a/dist/es-modules/stack/extension/index.js b/dist/es-modules/stack/extension/index.js new file mode 100644 index 00000000..ea04d20d --- /dev/null +++ b/dist/es-modules/stack/extension/index.js @@ -0,0 +1,247 @@ +import _typeof from "@babel/runtime/helpers/typeof"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import cloneDeep from 'lodash/cloneDeep'; +import { create, update, deleteEntity, fetch, query, upload, parseData } from '../../entity'; +import error from '../../core/contentstackError'; +import FormData from 'form-data'; +import { createReadStream } from 'fs'; +/** + * Extensions let you create custom fields and custom widgets that lets you customize Contentstack's default UI and behavior. Read more about Extensions. + * @namespace Extension + * */ + +export function Extension(http) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/extensions"; + + if (data.extension) { + Object.assign(this, cloneDeep(data.extension)); + this.urlPath = "/extensions/".concat(this.uid); + /** + * @description The Update Extension call lets you update an existing Extension. + * @memberof Extension + * @func update + * @returns {Promise} Promise for Extension instance. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).extension('extension_uid').fetch() + * .then((extension) => { + * extension.title = 'My Extension Type' + * return extension.update() + * }) + * .then((extension) => console.log(extension)) + * + */ + + this.update = update(http, 'extension'); + /** + * @description The Delete Extension call is used to delete an existing Extension permanently from your Stack. + * @memberof Extension + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).extension('extension_uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch Extension call fetches Extension details. + * @memberof Extension + * @func fetch + * @returns {Promise} Promise for Extension instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).extension('extension_uid').fetch() + * .then((extension) => console.log(extension)) + * + */ + + this.fetch = fetch(http, 'extension'); + } else { + /** + * @description The Upload is used to upload a new custom widget, custom field, dashboard Widget to a stack. + * @memberof Extension + * @func upload + * @returns {Promise} Promise for Extension instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const extension = { + * upload: 'path/to/file', + * title: 'Title', + * tags: [ + * 'tag1', + * 'tag2' + * ], + * data_type: 'text', + * title: 'Old Extension', + * multiple: false, + * config: {}, + * type: 'Type of extenstion you want to create widget/dashboard/field' + * } + * + * client.stack({ api_key: 'api_key'}).extension().upload(extension) + * .then((extension) => console.log(extension)) + */ + this.upload = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(data, params) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return upload({ + http: http, + urlPath: this.urlPath, + stackHeaders: this.stackHeaders, + formData: createExtensionFormData(data), + params: params + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 8: + throw error(response); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + throw error(_context.t0); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[0, 11]]); + })); + + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + /** + * @description The Create a extension call creates a new extension in a particular stack of your Contentstack account. + * @memberof Extension + * @func create + * @returns {Promise} Promise for Extension instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const extension = { + * tags: [ + * 'tag1', + * 'tag2' + * ], + * data_type: 'text', + * title: 'Old Extension', + * src: "Enter either the source code (use 'srcdoc') or the external hosting link of the extension depending on the hosting method you selected.", + * multiple: false, + * config: {}, + * type: 'field' + * } + * + * client.stack().extension().create({ extension }) + * .then((extension) => console.log(extension)) + */ + + + this.create = create({ + http: http + }); + /** + * @description The Query on Content Type will allow to fetch details of all or specific Content Type + * @memberof Extension + * @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 {Array} Array of ContentTyoe. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().extension().query({ query={"type":"field"}}) + * .then((extensions) => console.log(extensions)) + */ + + this.query = query({ + http: http, + wrapperCollection: ExtensionCollection + }); + } +} +export function ExtensionCollection(http, data) { + var obj = cloneDeep(data.extensions) || []; + var extensionCollection = obj.map(function (extensiondata) { + return new Extension(http, { + extension: extensiondata, + stackHeaders: data.stackHeaders + }); + }); + return extensionCollection; +} + +function createExtensionFormData(data) { + var formData = new FormData(); + + if (typeof data.title === 'string') { + formData.append('extension[title]', data.title); + } + + if (_typeof(data.scope) === 'object') { + formData.append('extension[scope]', "".concat(data.scope)); + } + + if (typeof data['data_type'] === 'string') { + formData.append('extension[data_type]', data['data_type']); + } + + if (typeof data.type === 'string') { + formData.append('extension[type]', data.type); + } + + if (data.tags instanceof Array) { + formData.append('extension[tags]', data.tags.join(',')); + } else if (typeof data.tags === 'string') { + formData.append('extension[tags]', data.tags); + } + + if (typeof data.multiple === 'boolean') { + formData.append('extension[multiple]', "".concat(data.multiple)); + } + + if (typeof data.enable === 'boolean') { + formData.append('extension[enable]', "".concat(data.enable)); + } + + var uploadStream = createReadStream(data.upload); + formData.append('extension[upload]', uploadStream); + return formData; +} \ No newline at end of file diff --git a/dist/es-modules/stack/globalField/index.js b/dist/es-modules/stack/globalField/index.js new file mode 100644 index 00000000..922ef8aa --- /dev/null +++ b/dist/es-modules/stack/globalField/index.js @@ -0,0 +1,200 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import cloneDeep from 'lodash/cloneDeep'; +import { create, update, deleteEntity, fetch, query, upload, parseData } from '../../entity'; +import error from '../../core/contentstackError'; +import FormData from 'form-data'; +import { createReadStream } from 'fs'; +/** + * GlobalField defines the structure or schema of a page or a section of your web or mobile property. To create global Fields for your application, you are required to first create a gloabl field. Read more about Global Fields. + * @namespace GlobalField + */ + +export function GlobalField(http) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.stackHeaders = data.stackHeaders; + this.urlPath = "/global_fields"; + + if (data.global_field) { + Object.assign(this, cloneDeep(data.global_field)); + this.urlPath = "/global_fields/".concat(this.uid); + /** + * @description The Update GlobalField call lets you update the name and description of an existing GlobalField. + * @memberof GlobalField + * @func update + * @returns {Promise} Promise for GlobalField instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).globalField('global_field_uid').fetch() + * .then((globalField) => { + * globalField.title = 'My New Content Type' + * globalField.description = 'Content Type description' + * return globalField.update() + * }) + * .then((globalField) => console.log(globalField)) + * + */ + + this.update = update(http, 'global_field'); + /** + * @description The Delete GlobalField call is used to delete an existing GlobalField permanently from your Stack. + * @memberof GlobalField + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).globalField('global_field_uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch GlobalField call fetches GlobalField details. + * @memberof GlobalField + * @func fetch + * @returns {Promise} Promise for GlobalField instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).globalField('global_field_uid').fetch() + * .then((globalField) => console.log(globalField)) + * + */ + + this.fetch = fetch(http, 'global_field'); + } else { + /** + * @description The Create a GlobalField call creates a new globalField in a particular stack of your Contentstack account. + * @memberof GlobalField + * @func create + * @returns {Promise} Promise for GlobalField instance + * + * @example + * import * as contentstac k from '@contentstack/management' + * const client = contentstack.client() + * const global_field = { + * title: 'First', + * uid: 'first', + * schema: [{ + * display_name: 'Name', + * uid: 'name', + * data_type: 'text' + * }] + * } + * client.stack().globalField().create({ global_field }) + * .then((globalField) => console.log(globalField)) + */ + this.create = create({ + http: http + }); + /** + * @description The Query on GlobalField will allow to fetch details of all or specific GlobalField + * @memberof GlobalField + * @func query + * @returns {Array} Array of GlobalField. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().globalField().query({ query: { name: 'Global Field Name' } }).find() + * .then((globalFields) => console.log(globalFields)) + */ + + this.query = query({ + http: http, + wrapperCollection: GlobalFieldCollection + }); + /** + * @description The Import a global field call imports a global field into a stack. + * @memberof GlobalField + * @func import + * @param {String} data.global_field path to file + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const data = { + * global_field: 'path/to/file.json', + * } + * client.stack({ api_key: 'api_key'}).globalField().import(data) + * .then((globalField) => console.log(globalField)) + * + */ + + this["import"] = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(data) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return upload({ + http: http, + urlPath: "".concat(this.urlPath, "/import"), + stackHeaders: this.stackHeaders, + formData: createFormData(data) + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", new this.constructor(http, parseData(response, this.stackHeaders))); + + case 8: + throw error(response); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + throw error(_context.t0); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[0, 11]]); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + } + + return this; +} +export function GlobalFieldCollection(http, data) { + var obj = cloneDeep(data.global_fields) || []; + var globalFieldCollection = obj.map(function (userdata) { + return new GlobalField(http, { + global_field: userdata, + stackHeaders: data.stackHeaders + }); + }); + return globalFieldCollection; +} + +function createFormData(data) { + var formData = new FormData(); + var uploadStream = createReadStream(data.global_field); + formData.append('global_field', uploadStream); + return formData; +} \ No newline at end of file diff --git a/dist/es-modules/stack/index.js b/dist/es-modules/stack/index.js new file mode 100644 index 00000000..1ca71fdc --- /dev/null +++ b/dist/es-modules/stack/index.js @@ -0,0 +1,975 @@ +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import _defineProperty from "@babel/runtime/helpers/defineProperty"; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +import cloneDeep from 'lodash/cloneDeep'; +import error from '../core/contentstackError'; +import { UserCollection } from '../user/index'; +import { Role } from './roles/index'; +import { create, query, update, deleteEntity, fetch } from '../entity'; +import { ContentType } from './contentType/index'; +import { GlobalField } from './globalField/index'; +import { DeliveryToken } from './deliveryToken/index'; +import { Environment } from './environment'; +import { Asset } from './asset'; +import { Locale } from './locale'; +import { Extension } from './extension'; +import { Webhook } from './webhook'; +import { Release } from './release'; +import { BulkOperation } from './bulkOperation'; +import { Label } from './label'; // import { format } from 'util' + +/** + * A stack is a space that stores the content of a project (a web or mobile property). Within a stack, you can create content structures, content entries, users, etc. related to the project. Read more about Stacks. + * @namespace Stack + */ + +export function Stack(http, data) { + var _this = this; + + this.urlPath = '/stacks'; + + if (data) { + if (data.stack) { + Object.assign(this, cloneDeep(data.stack)); + } else if (data.organization_uid) { + this.organization_uid = data.organization_uid; + } + } + + if (data && data.stack && data.stack.api_key) { + this.stackHeaders = { + api_key: this.api_key + }; + + if (this.management_token && this.management_token) { + this.stackHeaders.authorization = this.management_token; + delete this.management_token; + } + /** + * @description The Update stack call lets you update the name and description of an existing stack. + * @memberof Stack + * @func update + * @returns {Promise} Promise for Stack instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).fetch() + * .then((stack) => { + * stack.name = 'My New Stack' + * stack.description = 'My new test stack' + * return stack.update() + * }) + * .then((stack) => console.log(stack)) + * + */ + + + this.update = update(http, 'stack'); + /** + * @description The Delete stack call is used to delete an existing stack permanently from your Contentstack account. + * @memberof Stack + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch stack call fetches stack details. + * @memberof Stack + * @func fetch + * @returns {Promise} Promise for Stack instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).fetch() + * .then((stack) => console.log(stack)) + * + */ + + this.fetch = fetch(http, 'stack'); + /** + * @description Content type defines the structure or schema of a page or a section of your web or mobile property. + * @param {String} uid The UID of the ContentType you want to get details. + * @returns {ContenType} Instace of ContentType. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).contentType().create() + * .then((contentType) => console.log(contentType)) + * + * client.stack({ api_key: 'api_key'}).contentType('content_type_uid').fetch() + * .then((contentType) => console.log(contentType)) + */ + + this.contentType = function () { + var contentTypeUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (contentTypeUid) { + data.content_type = { + uid: contentTypeUid + }; + } + + return new ContentType(http, data); + }; + /** + * @description Locale allows you to create and publish entries in any language. + * @param {String} uid The UID of the Locale you want to get details. + * @returns {Locale} Instace of Locale. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).locale().create() + * .then((locale) => console.log(locale)) + * + * client.stack({ api_key: 'api_key'}).locale('locale_code').fetch() + * .then((locale) => console.log(locale)) + */ + + + this.locale = function () { + var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (code) { + data.locale = { + code: code + }; + } + + return new Locale(http, data); + }; + /** + * @description Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded in your Contentstack repository for future use. + * @param {String} uid The UID of the Asset you want to get details. + * @returns {Asset} Instace of Asset. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).asset().create() + * .then((asset) => console.log(asset)) + * + * client.stack({ api_key: 'api_key'}).asset('asset_uid').fetch() + * .then((asset) => console.log(asset)) + */ + + + this.asset = function () { + var assetUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (assetUid) { + data.asset = { + uid: assetUid + }; + } + + return new Asset(http, data); + }; + /** + * @description Global field defines the structure or schema of a page or a section of your web or mobile property. + * @param {String} uid The UID of the Global field you want to get details. + * @returns {ContenType} Instace of Global field. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).globalField().create() + * .then((globalField) => console.log(globalField)) + * + * client.stack({ api_key: 'api_key'}).globalField('globalField_uid').fetch() + * .then((globalField) => console.log(globalField)) + */ + + + this.globalField = function () { + var globalFieldUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (globalFieldUid) { + data.global_field = { + uid: globalFieldUid + }; + } + + return new GlobalField(http, data); + }; + /** + * @description Environment corresponds to one or more deployment servers or a content delivery destination where the entries need to be published. + * @param {String} uid The UID of the Environment you want to get details. + * @returns {Environment} Instace of Environment. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).globalField().create() + * .then((globalField) => console.log(globalField)) + * + * client.stack({ api_key: 'api_key'}).globalField('globalField_uid').fetch() + * .then((globalField) => console.log(globalField)) + */ + + + this.environment = function () { + var environmentUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (environmentUid) { + data.environment = { + name: environmentUid + }; + } + + return new Environment(http, data); + }; + /** + * @description Delivery Tokens provide read-only access to the associated environments. + * @param {String} deliveryTokenUid The UID of the Delivery Token field you want to get details. + * @returns {DeliveryToken} Instace of DeliveryToken. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).deliveryToken().create() + * .then((deliveryToken) => console.log(deliveryToken)) + * + * client.stack({ api_key: 'api_key'}).deliveryToken('deliveryToken_uid').fetch() + * .then((deliveryToken) => console.log(deliveryToken)) + */ + + + this.deliveryToken = function () { + var deliveryTokenUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (deliveryTokenUid) { + data.token = { + uid: deliveryTokenUid + }; + } + + return new DeliveryToken(http, data); + }; + /** + * @description Extensions let you create custom fields and custom widgets that lets you customize Contentstack's default UI and behavior. + * @param {String} extensionUid The UID of the Extension you want to get details. + * @returns {Extension} Instace of Extension. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).extension().create() + * .then((extension) => console.log(extension)) + * + * client.stack({ api_key: 'api_key'}).extension('extension_uid').fetch() + * .then((extension) => console.log(extension)) + */ + + + this.extension = function () { + var extensionUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (extensionUid) { + data.extension = { + uid: extensionUid + }; + } + + return new Extension(http, data); + }; + /** + * @description Webhooks allow you to specify a URL to which you would like Contentstack to post data when an event happens. + * @param {String} webhookUid The UID of the Webhook you want to get details. + * @returns {Webhook} Instace of Webhook. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).webhook().create() + * .then((webhook) => console.log(webhook)) + * + * client.stack({ api_key: 'api_key'}).webhook('webhook_uid').fetch() + * .then((webhook) => console.log(webhook)) + */ + + + this.webhook = function () { + var webhookUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (webhookUid) { + data.webhook = { + uid: webhookUid + }; + } + + return new Webhook(http, data); + }; + /** + * @description Labels allow you to group a collection of content within a stack. Using labels you can group content types that need to work together + * @param {String} uid The UID of the Label you want to get details. + * @returns {Label} Instace of Label. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).label().create() + * .then((label) => console.log(label)) + * + * client.stack({ api_key: 'api_key'}).label('label_uid').fetch() + * .then((label) => console.log(label)) + */ + + + this.label = function () { + var labelUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (labelUid) { + data.label = { + uid: labelUid + }; + } + + return new Label(http, data); + }; + /** + * @description You can pin a set of entries and assets (along with the deploy action, i.e., publish/unpublish) to a ‘release’, and then deploy this release to an environment. + * @param {String} releaseUid The UID of the Releases you want to get details. + * @returns {Release} Instance of Release. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).release().create() + * .then((release) => console.log(release)) + * + * client.stack({ api_key: 'api_key'}).release('release_uid').fetch() + * .then((release) => console.log(release)) + */ + + + this.release = function () { + var releaseUid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (releaseUid) { + data.release = { + uid: releaseUid + }; + } + + return new Release(http, data); + }; + /** + * Bulk operations such as Publish, Unpublish, and Delete on multiple entries or assets. + * @returns {BulkOperation} Instance of BulkOperation. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * const publishDetails = { + * entries: [ + * { + * uid: '{{entry_uid}}', + * content_type: '{{content_type_uid}}', + * version: '{{version}}', + * locale: '{{entry_locale}}' + * } + * ], + * assets: [{ + * uid: '{{uid}}' + * }], + * locales: [ + * 'en' + * ], + * environments: [ + * '{{env_name}}/env_uid}}' + * ] + * } + * client.stack({ api_key: 'api_key'}).bulkOperation().publish({ details: publishDetails }) + * .then((response) => { console.log(response.notice) }) + * + */ + + + this.bulkOperation = function () { + var data = { + stackHeaders: _this.stackHeaders + }; + return new BulkOperation(http, data); + }; + /** + * @description The Get all users of a stack call fetches the list of all users of a particular stack + * @memberof Stack + * @func users + * @returns {Array} Array of User's including owner of Stack + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).users() + * .then((users) => console.log(users)) + * + */ + + + this.users = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return http.get(_this.urlPath, { + params: { + include_collaborators: true + }, + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 3: + response = _context.sent; + + if (!response.data) { + _context.next = 8; + break; + } + + return _context.abrupt("return", UserCollection(http, response.data.stack)); + + case 8: + return _context.abrupt("return", error(response)); + + case 9: + _context.next = 14; + break; + + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + return _context.abrupt("return", error(_context.t0)); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 11]]); + })); + /** + * @description The Transfer stack ownership to other users call sends the specified user an email invitation for accepting the ownership of a particular stack. + * @memberof Stack + * @func transferOwnership + * @param {String} email The email address of the user to whom you wish to transfer the ownership of the stack. + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).transferOwnership('emailId') + * .then((response) => console.log(response.notice)) + * + */ + + this.transferOwnership = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(email) { + var response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return http.post("".concat(_this.urlPath, "/transfer_ownership"), { + transfer_to: email + }, { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 3: + response = _context2.sent; + + if (!response.data) { + _context2.next = 8; + break; + } + + return _context2.abrupt("return", response.data); + + case 8: + return _context2.abrupt("return", error(response)); + + case 9: + _context2.next = 14; + break; + + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](0); + return _context2.abrupt("return", error(_context2.t0)); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, null, [[0, 11]]); + })); + + return function (_x) { + return _ref2.apply(this, arguments); + }; + }(); + /** + * @description The Get stack settings call retrieves the configuration settings of an existing stack. + * @memberof Stack + * @func settings + * @returns {Object} Configuration settings of stack. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).settings() + * .then((settings) => console.log(settings)) + * + */ + + + this.settings = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var response; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return http.get("".concat(_this.urlPath, "/settings"), { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 3: + response = _context3.sent; + + if (!response.data) { + _context3.next = 8; + break; + } + + return _context3.abrupt("return", response.data.stack_settings); + + case 8: + return _context3.abrupt("return", error(response)); + + case 9: + _context3.next = 14; + break; + + case 11: + _context3.prev = 11; + _context3.t0 = _context3["catch"](0); + return _context3.abrupt("return", error(_context3.t0)); + + case 14: + case "end": + return _context3.stop(); + } + } + }, _callee3, null, [[0, 11]]); + })); + /** + * @description The Reset stack settings call resets your stack to default settings, and additionally, lets you add parameters to or modify the settings of an existing stack. + * @memberof Stack + * @func resetSettings + * @returns {Object} Configuration settings of stack. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).resetSettings() + * .then((settings) => console.log(settings)) + * + */ + + this.resetSettings = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + var response; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.prev = 0; + _context4.next = 3; + return http.post("".concat(_this.urlPath, "/settings"), { + stack_settings: { + discrete_variables: {}, + stack_variables: {} + } + }, { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 3: + response = _context4.sent; + + if (!response.data) { + _context4.next = 8; + break; + } + + return _context4.abrupt("return", response.data.stack_settings); + + case 8: + return _context4.abrupt("return", error(response)); + + case 9: + _context4.next = 14; + break; + + case 11: + _context4.prev = 11; + _context4.t0 = _context4["catch"](0); + return _context4.abrupt("return", error(_context4.t0)); + + case 14: + case "end": + return _context4.stop(); + } + } + }, _callee4, null, [[0, 11]]); + })); + /** + * @description The Add stack settings call lets you add settings for an existing stack. + * @memberof Stack + * @func addSettings + * @returns {Object} Configuration settings of stack. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).addSettings({ key: 'value' }) + * .then((settings) => console.log(settings)) + * + */ + + this.addSettings = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() { + var stackVariables, + response, + _args5 = arguments; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + stackVariables = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {}; + _context5.prev = 1; + _context5.next = 4; + return http.post("".concat(_this.urlPath, "/settings"), { + stack_settings: { + stack_variables: stackVariables + } + }, { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 4: + response = _context5.sent; + + if (!response.data) { + _context5.next = 9; + break; + } + + return _context5.abrupt("return", response.data.stack_settings); + + case 9: + return _context5.abrupt("return", error(response)); + + case 10: + _context5.next = 15; + break; + + case 12: + _context5.prev = 12; + _context5.t0 = _context5["catch"](1); + return _context5.abrupt("return", error(_context5.t0)); + + case 15: + case "end": + return _context5.stop(); + } + } + }, _callee5, null, [[1, 12]]); + })); + /** + * @description The Share a stack call shares a stack with the specified user to collaborate on the stack. + * @memberof Stack + * @func share + * @param {Array} emails - Email ID of the user with whom you wish to share the stack + * @param {Array} roles - The role uid that you wish to assign the user. + * @returns {Object} Response Object. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).share([ "manager@example.com" ], { "manager@example.com": [ "abcdefhgi1234567890" ] }) + * .then((response) => console.log(response.notice)) + * + */ + + this.share = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { + var emails, + roles, + response, + _args6 = arguments; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + emails = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : []; + roles = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.prev = 2; + _context6.next = 5; + return http.post("".concat(_this.urlPath, "/share"), { + emails: emails, + roles: roles + }, { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 5: + response = _context6.sent; + + if (!response.data) { + _context6.next = 10; + break; + } + + return _context6.abrupt("return", response.data); + + case 10: + return _context6.abrupt("return", error(response)); + + case 11: + _context6.next = 16; + break; + + case 13: + _context6.prev = 13; + _context6.t0 = _context6["catch"](2); + return _context6.abrupt("return", error(_context6.t0)); + + case 16: + case "end": + return _context6.stop(); + } + } + }, _callee6, null, [[2, 13]]); + })); + /** + * @description The Unshare a stack call unshares a stack with a user and removes the user account from the list of collaborators. + * @memberof Stack + * @func unShare + * @param {String} email The email ID of the user from whom you wish to unshare the stack. + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).unShare('email@id.com') + * .then((response) => console.log(response.notice)) + * + */ + + this.unShare = /*#__PURE__*/function () { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(email) { + var response; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.prev = 0; + _context7.next = 3; + return http.post("".concat(_this.urlPath, "/unshare"), { + email: email + }, { + headers: _objectSpread({}, cloneDeep(_this.stackHeaders)) + }); + + case 3: + response = _context7.sent; + + if (!response.data) { + _context7.next = 8; + break; + } + + return _context7.abrupt("return", response.data); + + case 8: + return _context7.abrupt("return", error(response)); + + case 9: + _context7.next = 14; + break; + + case 11: + _context7.prev = 11; + _context7.t0 = _context7["catch"](0); + return _context7.abrupt("return", error(_context7.t0)); + + case 14: + case "end": + return _context7.stop(); + } + } + }, _callee7, null, [[0, 11]]); + })); + + return function (_x2) { + return _ref7.apply(this, arguments); + }; + }(); + /** + * @description A role is a collection of permissions that will be applicable to all the users who are assigned this role. + * @memberof Stack + * @func role + * @param {String=} uid The UID of the role you want to get details. + * @returns {Role} Instance of Role. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).role().create({ + * "role": + * { + * "name":"testRole", + * "description":"", + * "rules":[...], + * } + * }) + * .then((role) => console.log(role)) + * + * client.stack({ api_key: 'api_key'}).role('role_uid').fetch()) + * .then((role) => console.log(role)) + * + */ + + + this.role = function () { + var uid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var data = { + stackHeaders: _this.stackHeaders + }; + + if (uid) { + data.role = { + uid: uid + }; + } + + return new Role(http, data); + }; + } else { + /** + * @description The Create stack call creates a new stack in your Contentstack account. + * @memberof Stack + * @func create + * @returns {Promise} Promise for Stack instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.organization('org_uid').stack().create({name: 'My New Stack'}) + * .then((stack) => console.log(stack)) + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().create({name: 'My New Stack'}, { organization_uid: 'org_uid' }) + * .then((stack) => console.log(stack)) + */ + this.create = create({ + http: http, + params: this.organization_uid ? { + organization_uid: this.organization_uid + } : null + }); + /** + * @description The Query on Stack will allow to fetch details of all or specific Stack. + * @memberof Stack + * @func query + * @param {Boolean} include_collaborators Set this parameter to 'true' to include the details of the stack collaborators. + * @param {Boolean} include_stack_variablesSet this to 'true' to display the stack variables. Stack variables are extra information about the stack, such as the description, format of date, format of time, and so on. Users can include or exclude stack variables in the response. + * @param {Boolean} include_discrete_variables Set this to 'true' to view the access token of your stack. + * @param {Boolean} include_count Set this to 'true' to include in the response the total count of the stacks owned by or shared with a user account. + * @param {Object} query Queries that you can use to fetch filtered results. + * @returns {ContentstackCollection} Instance of ContentstackCollection. + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack().query({ query: { name: 'Stack Name' } }).find() + * .then((stack) => console.log(stack)) + */ + + this.query = query({ + http: http, + wrapperCollection: StackCollection + }); + } + + return this; +} +export function StackCollection(http, data) { + var stacks = data.stacks || []; + var obj = cloneDeep(stacks); + var stackCollection = obj.map(function (userdata) { + return new Stack(http, { + stack: userdata + }); + }); + return stackCollection; +} \ No newline at end of file diff --git a/dist/es-modules/stack/label/index.js b/dist/es-modules/stack/label/index.js new file mode 100644 index 00000000..6d35518e --- /dev/null +++ b/dist/es-modules/stack/label/index.js @@ -0,0 +1,114 @@ +import cloneDeep from 'lodash/cloneDeep'; +import { update, deleteEntity, fetch, query, create } from '../../entity'; +/** + * Labels allow you to group a collection of content within a stack. Using labels you can group content types that need to work together. Read more about Labels. + * @namespace Label + */ + +export function Label(http, data) { + this.stackHeaders = data.stackHeaders; + this.urlPath = "/labels"; + + if (data.label) { + Object.assign(this, cloneDeep(data.label)); + this.urlPath = "/labels/".concat(this.uid); + /** + * @description The Update label call is used to update an existing label. + * @memberof Label + * @func update + * @returns {Promise} Promise for Label instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).label('label_uid').fetch() + * .then((label) => { + * label.name = 'My New Content Type' + * return label.update() + * }) + * .then((label) => console.log(label)) + * + */ + + this.update = update(http, 'label'); + /** + * @description The Delete label call is used to delete a specific label. + * @memberof Label + * @func delete + * @returns {Object} Response Object. + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).label('label_uid').delete() + * .then((response) => console.log(response.notice)) + */ + + this["delete"] = deleteEntity(http); + /** + * @description The fetch Label returns information about a particular label of a stack. + * @memberof Label + * @func fetch + * @returns {Promise} Promise for Label instance + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * + * client.stack({ api_key: 'api_key'}).label('label_uid').fetch() + * .then((label) => console.log(label)) + * + */ + + this.fetch = fetch(http, 'label'); + } else { + /** + * @description The Create an label call creates a new label. + * @memberof Label + * @func create + * @returns {Promise} Promise for Label instance + * + * @example + * import * as contentstack from '@contentstack/management' + * const client = contentstack.client() + * const label = { + * name: 'First label', + * content_types: [singlepageCT.content_type.uid] + * } + * client.stack().label().create({ label }) + * .then((label) => console.log(label)) + */ + this.create = create({ + http: http + }); + /** + * @description The Query on Label will allow to fetch details of all or specific Label. + * @memberof Label + * @param {Object} params - URI parameters + * @prop {Object} params.query - Queries that you can use to fetch filtered results. + * @func query + * @returns {Array