Skip to content

This repository holds the api reference of the Contentstack's app-sdk

License

Notifications You must be signed in to change notification settings

contentstack/app-sdk-docs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

76 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Contentstack App SDK API Reference

In this document, we will discuss the API requests that a custom location can use to communicate with Contentstack.

How to Include App SDK into Your Project

To include the app-sdk library in your React app or project, you need to open command prompt and run the following command:

npm install @contentstack/app-sdk

Alternatively, you can add it inside script tag:

<scriptsrc="https://unpkg.com/@contentstack/app-sdk/dist/index.js" integrity="sha512-mcJn/xSGuDGTvKiBvPfjLxbLfRpByRNzdbyldfpNie10BdFHgy7hRxACw3mQ3xbx752N85eqgMPIm8lb4Aq8pw==" crossorigin="anonymous"></script>

The above command will install the app-sdk library in your project which contains the necessary toolkit you need to manage installed apps on specific locations.

Top level Objects

Below we have listed some of the top-level objects used in the App SDK.

  • Location: It's an object that represents all locations from the Contentstack UI.
  • Store: It refers to a class that is used by a location to store your data in the local storage.
  • Stack: It's a class representing the current stack in the Contentstack UI.
  • Window Frame: It refers to a class that represents an iframe window from the Contentstack UI.

    Note: This class is not available for Custom Widgets.

  • Entry: It's a class that represents an entry from the Contentstack UI.

    Note: It's not available for the Dashboard Widget extension.

  • Modal: It's a class that represents a modal dialog opened from the app within the Contentstack UI.

Top level Methods

The App SDK provides several top-level methods that retrieve app-related information.

  • getConfig: Retrieves the configuration set for the app. This method allows easy access to the app's configuration data set on the app configuration page.
  • getCurrentLocation: Returns the current UI location type of the app.
  • getCurrentRegion: : Retrieves the Contentstack Region on which the app is running.
  • getAppVersion: Returns the version of the app currently installed.

    Note: The getAppVersion method is not available for JSON RTE Plugins.

Method NameDescriptionReturn Type
getConfigRetrieves the configuration set for the app.Promise<Object>
getCurrentLocationGets the type of currently running UI location of the app."RTE" | "FIELD" | "DASHBOARD" | "WIDGET" | "APP_CONFIG_WIDGET" | "ASSET_SIDEBAR_WIDGET" | "FULL_PAGE_LOCATION" | "ENTRY_FIELD_LOCATION" | "FIELD_MODIFIER_LOCATION"
getCurrentRegionGets the Contentstack Region on which the app is running."UNKNOWN" | "NA" | "EU" | "AZURE_NA" | "AZURE_EU"
getAppVersionGets the version of the app currently installed.Promise<Number | null>

Example

// javascriptContentstackAppSDK.init().then(asyncfunction(appSdk){// Retrieve the app configurationconstappConfig=awaitappSdk.getConfig();// Get the current UI location of the appconstcurrentLocation=appSdk.getCurrentLocation();// Get the Contentstack Region of the appconstcurrentRegion=appSdk.getCurrentRegion();// Get the version of the appconstappVersion=awaitappSdk.getAppVersion();});

Supported Locations

Locations refers to the position or the placement of the app (sidebar widget, custom field, etc). As of now, the following locations are supported:

  • CustomField: It's an object representing the current Custom field reference in the Contentstack UI.
  • DashboardWidget: It's an object representing the Dashboard widget reference in the Contentstack UI.
  • SidebarWidget: It's an object representing the current Sidebar widget reference in the Contentstack UI.
  • AppConfigWidget: It's an object representing the current App configuration for the current App in the Contentstack UI.
  • FieldModifierLocation: It's an object representing the Field Modifier reference over the field in the Contentstack UI.
  • ContentTypeSidebarWidget: It's an object representing the Content Type Sidebar Widget in the Contentstack UI.

External

  • Promise: The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
  • localStorage: The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

Using the Contentstack App SDK

Kind: global class

ContentstackAppSDK

ContentstackAppSDK.SDK_VERSION : string

The above defines the version of the Contentstack UI App SDK.

Kind: static property of ContentstackAppSDK

ContentstackAppSDK.init() ⇒ Promise

To start using the APP SDK, you first need to include the Contentstack UI App SDK and Contentstack Venus UI Stylesheet in your HTML file and then call ContentstackAppSDK.init on component mount.

Kind: The static method of ContentstackAppSDK

Returns: Promise - A promise object which will be resolved with an instance of the Location class which is instantiated using the data received from the Contentstack UI.

Example(App Config Widget)

// javascriptContentstackAppSDK.init().then(function(appSdk){// Get AppConfigWidget object// this is only initialized on the App configuration page.// on other locations this will return undefined.varappConfigWidget=awaitappSdk.location.AppConfigWidget;// fetch all Installation configuration related to// 1. App Configuration// 2. Server Configuration// 3. Webhooks channels// 4. UI Locations configured in the appvarinstallationData=awaitappConfigWidget.getInstallationData();// Update all Installation configuration related to// 1. App Configuration// 2. Server Configuration// 3. Webhooks channels// 4. UI Locations configured in the appvargetInstallationData=awaitappConfigWidget.setInstallationData(installationData);});

Example(Custom Field)

// javascriptContentstackAppSDK.init().then(function(appSdk){// Get CustomField object// this is only initialized on the Entry create/edit page.// on other locations this will return undefined.varcustomField=awaitappSdk.location.CustomField;// fetch app configurationvarappConfig=awaitappSdk.getConfig();// fetch entry informationvarfieldData=awaitcustomField.entry.getData();});

Example(Sidebar Widget)

// javascriptContentstackAppSDK.init().then(function(location){// Get SidebarWidget object// this is only initialized on the Entry edit page.// on other locations this will return undefined.varsidebarWidget=awaitappSdk.location.SidebarWidget;// fetch app configurationvarappConfig=awaitappSdk.getConfig();// fetch entry informationvarfieldData=awaitsidebarWidget.entry.getData();});

Example(Dashboard Widget)

// javascriptContentstackAppSDK.init().then(function(location){// Get SidebarWidget object// this is only initialized on the Entry edit page.// on other locations this will return undefined.vardashboardWidget=awaitappSdk.location.DashboardWidget;// fetch app configurationvarappConfig=awaitappSdk.getConfig();// fetch stack informationvarstackData=awaitappSdk.stack.getData();});

Example(Field Modifier location)

// javascriptContentstackAppSDK.init().then(function(appSdk){// Get FieldModifierLocation object// this is only initialized on the Entry create/edit page.// on other locations this will return undefined.varfieldModifierLocation=awaitappSdk.location.FieldModifierLocation;// fetch app configurationvarappConfig=awaitappSdk.getConfig();// fetch entry informationvarfieldData=awaitfieldModifierLocation.entry.getData();});

CustomField

It is an object representing the current Custom field reference in the Contentstack UI.

Kind: The instance property of AppConfigWidget

CustomField

customfield.fieldConfig : Object

The above method gives you the instance configuration parameters set from the content type builder page in the field settings. This is only available for the Custom Field location.

Kind: instance property of CustomField

customfield.field : Field

This method gives you the custom field object which allows you to interact with the field. Please note that it is available only for the Custom Field location.

Kind: instance property of CustomField

customfield.entry : Entry

This method gives you the entry object which allows you to interact with the current entry. Please note that it is not available for the Dashboard Widget location.

Kind: instance property of CustomField

customfield.frame : Frame

The frame object provides users with methods that allow them to adjust the size of the iframe containing the location. Note that it is not available for the custom widgets location.

Kind: instance property of CustomField

customfield.stack : Stack

This method returns the stack object which allows users to read and manipulate a range of objects in a stack.

Kind: instance property of CustomField

DashboardWidget

DashboardWidget

Kind: instance property of DashboardWidget

DashboardWidget

dashboardWidget.frame : Frame

This frame object provides users with methods that allow them to adjust the size of the iframe that contains the extension. Not available in case of custom widgets.

Kind: instance property of Location

dashboardWidget.stack : Stack

This method returns the stack object which allows users to read and manipulate a range of objects in a stack.

Kind: instance property of Location

SidebarWidget

It is an object representing the current Sidebar widget reference in the Contentstack UI.

Kind: instance property of SidebarWidget

SidebarWidget

extension.entry : Entry

This gives you the entry object to interact with the current entry. Please note that it is not available for the Dashboard Widget extension.

Kind: instance property of Extension

extension.stack : Stack

This method returns the stack object to read and manipulate a range of objects in a stack.

Kind: instance property of Extension

AssetSidebarWidget

It is an object representing the current Asset Sidebar Widget reference in the Contentstack UI.

  • getData()
  • setData(asset: Partial)
  • syncAsset()
  • updateWidth(width: number)
  • replaceAsset(file: File)
  • onSave(callback: anyFunction)
  • onChange(callback: anyFunction)
  • onPublish(callback: anyFunction)
  • onUnPublish(callback: anyFunction)
  • AssetData

getData()

This method returns the object representing the current asset.

setData(asset: Partial<AssetData>)

This method modifies the properties of the current asset.

syncAsset()

If your asset has been modified externally, you can use this method to load the new asset and sync its settings with the current asset.

updateWidth(width: number)

This method is used to modify the width of the asset sidebar panel. Using this method, you can resize the panel depending on the resolution of your content.

replaceAsset(file: File)

This method is used to replace the current asset with a new file. Unlike setData(), where you can only modify the properties, you can use this method to replace the actual file.

onSave(callback: anyFunction)

This is a callback function that runs after you save the asset settings.

onChange(callback: anyFunction)

This is a callback function that runs every time the user modifies the asset data.

onPublish(callback: anyFunction)

This is a callback function that is executed after a user publishes an asset.

onUnPublish(callback: anyFunction)

This is a callback function that is executed after you unpublish an asset.

AssetData

It is the property that you can modify using the setData() method.

AppConfigWidget

It's an object representing the current App configuration for the current App in the Contentstack UI.

Kind: instance property of AppConfigWidget

AppConfigWidget

appconfig.getInstallationData : InstallationData

This method gives you the complete installation data.

Kind: instance property of AppConfigWidget

appconfig.setInstallationData : InstallationData

This method updates installation data for the app.

Kind: instance property of AppConfigWidget

appconfig.setValidity(isValid: boolean, options: { message: string }) : Promise

The appconfig.setValidity method is used to set the validation state of the app in the Contentstack App Config location. By invoking this method with the isValid parameter as false, the user will be prevented from saving the configuration. Additionally, an optional message parameter can be provided to display a custom error message.

Parameters

  • isValid (boolean): Specifies whether the app configuration is considered valid (true) or invalid (false).
  • options (object): An optional object containing the following property:
    • message (string): A custom error message to be displayed when the configuration is invalid.

Kind: instance property of AppConfigWidget

// JavaScript// Initialize ContentstackAppSDKContentstackAppSDK.init().then(asyncfunction(appSdk){// Get the AppConfigWidget objectconstappConfigWidget=awaitappSdk.location.AppConfigWidget;// Set validity to false, notifying the user that incorrect inputs have been entered.appConfigWidget.installation.setValidity(false,{message: 'Please enter valid inputs'});});

FieldModifierLocation

It is an object representing the field modifier UI location in the Contentstack UI.

Kind: The instance property of FieldModifierLocation

FieldModifierLocation

FieldModifierLocation.field : Field

This method gives you the current field object which allows you to interact with the field.

Kind: instance property of FieldModifierLocation

field.uid : string

The UID of the current field is defined in the content type of the entry.

Kind: instance property of Field

field.data_type : string

The data type of the current field is set using this method.

Kind: instance property of Field

field.schema : Object

The schema of the current field (schema of fields such as ‘Single Line Textbox’, ‘Number’, and so on) is set using this method.

Kind: instance property of Field

field.setData(data) ⇒ Promise

Sets the data for the current field.

Kind: instance method of FieldReturns: Promise - A promise object which is resolved when data is set for a field. Note: The data set by this function will only be saved when the user saves the entry.

ParamTypeDescription
dataObject | string | numberData to be set on the field

field.getData(options) ⇒ Object | string | number

Gets the data of the current field.

Kind: instance method of FieldReturns: Object | string | number - Returns the field data.

ParamTypeDescription
optionsObjectOptions object for getData() method.
options.resolvedbooleanIf the resolved parameter is set to true for the File field, then the method will return a resolved asset object along with all the field metadata, e.g. 'field.getData({resolved:true})'.

field.onChange(callback)

The field.onChange() function is called when another extension programmatically changes the data of the current extension field using the field.setData() function. This function is only available for extension fields that support the following data types: text, number, boolean, or date.

Kind: instance method of Field

ParamTypeDescription
callbackfunctionThe function to be called when an entry is published.

FieldModifierLocation.entry :

This method gives you the entry, object which allows you to interact with the current entry.

Kind: instance property of FieldModifierLocation

entry.content_type : Object

Gets the content type of the current entry.

Kind: instance property of Entry

entry.locale : string

Gets the locale of the current entry.

Kind: instance property of Entry

entry.getData() ⇒ Object

Gets data of the current entry.

Kind: instance method of EntryReturns: Object - Returns entry data.

entry.getField(uid, options?) ⇒ Object

It gets the field object, allowing you to interact with it. This object will support all the methods and properties that work with the extension.field. Note: For fields initialized using the getFields function, the setData() function currently works only for the following fields: single_line, multi_line, RTE, markdown, select, number, boolean, date, link, and extension of data type text, number, boolean, and date.

Kind: instance method of EntryReturns: Object - Field object

ParamTypeDescription
uidstringUnique ID of the field
options.useUnsavedSchemabooleanGets the unsaved draft data of the field

Example

varfield=entry.getField("field_uid");varfieldSchema=field.schema;varfieldUid=field.uid;varfieldData=field.getData();

entry.onSave(callback)

This onSave() function executes the callback function every time an entry is saved.

Kind: instance method of Entry

ParamTypeDescription
callbackfunctionThe function to be called when an entry is saved.

entry.onChange(callback)

The onChange() function executes the callback function every time an entry has been updated.

Kind: instance method of Entry

ParamTypeDescription
callbackfunctionThe function to be called when an entry is updated.

entry.onPublish(callback)

The onPublish() function executes the callback function every time an entry has been published with the respective payload.

Kind: instance method of Entry

ParamTypeDescription
callbackfunctionThe function to be called when an entry is published.

entry.onUnPublish(callback)

The onPublish() function executes the callback function every time an entry has been unpublished with the respective payload.

Kind: instance method of Entry

ParamTypeDescription
callbackfunctionThe function to be called when an entry is unpublished.

entry.getTags(options?) ⇒ Array

Gets the tags of the current entry. By default, this method gets the saved tags, but you can get the draft tags by setting the options.useUnsavedSchema parameter.

Kind: instance method of EntryReturns: Array - List of tags

ParamTypeDescription
options.useUnsavedSchemabooleanGets the unsaved draft data of the field

entry.setTags(tags) ⇒ Array

Sets the tags in the entry.

Kind: instance method of EntryReturns: Array - List of tags

ParamTypeDescription
tagsArrayThe tags to be saved

FieldModifierLocation.stack : Stack

This method returns the stack object which allows users to read and manipulate a range of objects in a stack.

Kind: instance property of FieldModifierLocation

FieldModifierLocation.frame: Frame

The frame object provides users with methods that allow them to adjust the size of the iframe containing the UI location.

Kind: instance property of FieldModifierLocation

frame.updateDimension({height?, width?}) ⇒ Promise

This method updates the extension dimensions on the Contentstack UI. If the dimensions are not provided, it will update the dimensions of the extension to the dimensions of the content.

Kind: instance method of frame

Returns: Promise - A promise object which will be resolved when Contentstack UI sends an acknowledgement stating that the height has been updated.

ParameterTypeDescription
config.heightnumberDesired height of the iframe window
config.widthnumberDesired width of the iframe window

frame.enableAutoResizing() ⇒ frame

This method enables the auto resizing of the extension height.

Kind: instance method of frame

Returns: frame

frame.disableAutoResizing() ⇒ frame

This method disables the auto resizing of the extension height.

Kind: instance method of frame

Returns: frame.

frame.preventFrameClose(state: boolean) ⇒ Promise<void>

The frame.preventFrameClose method allows you to manage the default closing behavior of the app when the user clicks outside its frame. By default, the app is closed in such scenarios. This method enables you to control and customize the closing behavior based on your requirements.

Kind: instance method of frame

ParameterTypeDescription
statebooleanState to control the default closing behavior. Set to true to prevent the frame from closing on click outside, and false to revert to the default behavior.
// JavaScriptContentstackAppSDK.init().then(asyncfunction(appSdk){// Get the FieldModifierLocation objectconstfieldModifierLocation=awaitappSdk.location.FieldModifierLocation;// To disable the automatic closure of the app frame when the user clicks outsidefieldModifierLocation.frame.preventFrameClose(true);});

ContentTypeSidebarWidget

It is an object representing the Content Type Sidebar Widget in the Contentstack UI.

Kind: The instance property of ContentTypeSidebarWidget

ContentTypeSidebarWidget.getData() ⇒ ContentType

This method retrieves the current content type data of the sidebar widget.

Kind: instance method of ContentTypeSidebarWidget

Returns: ContentType - The current content type data.

ContentTypeSidebarWidget.onSave(callback)

Executes the specified callback function each time the content type is saved. The callback function receives the updated content type data as an argument.

Kind: instance method of ContentTypeSidebarWidget

ParamTypeDescription
callbackfunctionFunction called with the updated content type data on save event

Throws: Will throw an error if the provided callback is not a function.

Example

constsidebarWidget=newContentTypeSidebarWidget(initData,connection,emitter);// Register onSave callback to execute on each save event.sidebarWidget.onSave((updatedContentType)=>{console.log("Content type saved:",updatedContentType);});

frame

It is a class representing an iframe window from the Contentstack UI. Please note that it is not available for Custom Widgets.

Kind: global class

frame

frame.enableResizing() ⇒ Promise

This method activates the resize button that gives you the provision to resize your Dashboard Widget.

Kind: instance method of frame

Returns: Promise - A promise object which will resolve when a resize button is visible on the Dashboard Widget.

frame.onDashboardResize(callback) ⇒ boolean

This function executes the callback function whenever a Dashboard Widget extension is maximized or minimized. Please note that it is only applicable for Dashboard Widget extensions.

Kind: instance method of frame

Returns: boolean - Will return true

ParameterTypeDescription
callbackfunctionFunction to be called when a Dashboard Widget extension is maximized or minimized

frame.updateHeight(height) ⇒ Promise

This method updates the extension height on the Contentstack UI. If the ‘height’ argument is not passed, it will calculate the scroll height and set the height of the location window accordingly.

Kind: instance method of frame

Returns: Promise - A promise object which will be resolved when Contentstack UI sends an acknowledgement stating that the height has been updated.

ParameterTypeDescription
heightstring | numberDesired height of the iframe window

frame.enableAutoResizing() ⇒ frame

This method enables the auto resizing of the extension height.

Kind: instance method of frame

Returns: frame

frame.disableAutoResizing() ⇒ frame

This method disables the auto resizing of the extension height.

Kind: instance method of frame

Returns: frame.

Stack

It is a class representing the current stack in Contentstack UI.

Kind: global class

Stack

stack.ContentType

Kind: instance class of Stack

See: ContentType

.ContentType

new this.ContentType(uid)

A content type defines the structure or the schema of a page or a section of your web or mobile property.

ParameterTypeDescription
uidstringUID of content type

Example

extension.stack.ContentType('content_type_uid')

contentType.Entry

Kind: instance class of ContentType

See: Entries

new Entry()

An entry is the actual piece of content created using one of the defined content types.

entry.only([key], values) ⇒ Entry

This method is used to show the selected fields of an entry in the result set.

Kind: instance method of Entry

ParameterTypeDefaultDescription
[key]StringBASESingle field of an entry
valuesArrayArray of fields to be shown in the result set

Example( Only with field UID )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").only("title").fetch();

Example( Only with field UID )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").only("BASE","title").fetch();

Example( Only with field UIDs(array) )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").only(["title","description"]).fetch();
entry.except([key], values) ⇒ Entry

This method is used to hide the selected fields of an entry in the result set.

Kind: instance method of Entry

ParameterTypeDefaultDescription
[key]StringBASESingle field of an entry
valuesArrayArray of fields to be hidden in the result set

Example( Except with field uid )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").except("title").fetch();

Example( Except with field uid )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").except("BASE","title").fetch();

Example( Except with field uids(array) )

extension.stack.ContentType("content_type_uid").Entry("bltsomething123").except(["title","description"]).fetch();
entry.addParam(key, value) ⇒ Entry

This method includes a query parameter in a query.

Kind: instance method of Entry

Returns: Entry - Returns

ParameterTypeDescription
keystringKey of the parameter
valuestringValue of the parameter

Example

extension.stack.ContentType("content_type_uid").Entry("uid").addParam("include_count","true").fetch().then().catch();
entry.getReferences() ⇒ Promise

This method fetches all the entries in which the current entry is referenced.

Kind: instance method of Entry

Returns: Promise - Required data if resolved successfully

Additional Resource:Learn more about Entry references

Example

extension.stack.ContentType("content_type_uid").Entry("uid").getReferences().then().catch();
entry.delete() ⇒ Promise

This method deletes an existing entry.

Kind: instance method of Entry

Returns: Promise - Required data if resolved successfully

Additional Resource: Learn more about [Deleting an Entry](https://www.contentstack.com/docs/apis/content-management-api/#delete-an-entry| Delete Entry).

Example

extension.stack.ContentType("content_type_uid").Entry("uid").delete().then().catch();
entry.fetch() ⇒ Promise

This method fetches information of a specific entry.

Kind: instance method of Entry

Returns: Promise - Required data if resolved successfully.

Additional Resource: Learn more about Fetching a Single Entry.

Example

extension.stack.ContentType("content_type_uid").Entry("uid").fetch().then().catch();
entry.includeReference() ⇒ Entry

This method is used to include referenced entries from other content types.

Kind: instance method of Entry

Example( .includeReference with reference_field_uids as array )

stack.ContentType("contenttype_uid").Entry("bltsomething123").includeReference(["category","author"]).fetch();

Example( .includeReference with reference_field_uids )

stack.ContentType("contenttype_uid").Entry("bltsomething123").includeReference("category","author").fetch();
entry.language(languageCode) ⇒ Entry

This method is used to set the language code of which you want to retrieve the data.

Kind: instance method of Entry

ParameterTypeDescription
languageCodeStringLanguage code, for e.g. ‘en-us’, ‘ja-jp’, and so on.

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").language("en-us").fetch();
entry.environment(environment_uid) ⇒ Entry

This method is used to set the environment name of which you want to retrieve the data.

Kind: instance method of Entry

ParameterTypeDescription
environment_uidStringUID/Name of environment.

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").environment("development").fetch();
entry.addQuery(key, value) ⇒ Entry

This method is used to add a query to an entry object.

Kind: instance method of Entry

ParameterTypeDescription
keyStringKey of the query
valueStringValue of the query

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").addQuery("include_schema",true).fetch();
entry.includeSchema() ⇒ Entry

This method is used to include the schema of the current content type in the result set along with the entry/entries.

Kind: instance method of Entry

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").includeSchema().fetch();
entry.includeContentType() ⇒ Entry

This method is used to include the current content type in the result set along with the entry(ies).

Kind: instance method of Entry

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").includeContentType().fetch();
entry.includeOwner() ⇒ Entry

This method is used to include the owner of the entry(ies) in the result set.

Kind: instance method of Entry

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").includeOwner().fetch();
entry.getLanguages() ⇒ Promise

This method returns the details of all languages in which the entry is localized.

Kind: instance method of Entry

Example

extension.stack.ContentType("contenttype_uid").Entry("bltsomething123").getLanguages();
entry.unlocalize(locale) ⇒ Promise

This method is used to unlocalize an entry.

Kind: instance method of Entry

ParameterTypeDescription
localestringLocale in which the entry is to be unlocalized.

Example

extension.stack.ContentType('contenttype_uid').Entry('bltsomething123').unlocalize('fr-fr').then(...).catch(...);
entry.publish(payload, api_version="") ⇒ Promise

This method lets you publish an entry either immediately or schedule it to be published automatically at a later date/time.

Kind: instance method of Entry

ParameterTypeDescription
payloadobjectPayload for the request.
api_versionstringSend api version in headers.(optional argument)

Example

extension.stack.ContentType('contenttype_uid').Entry('bltsomething123').publish({"entry": {"environments": ["development"],"locales": ["en-us"]},"locale": "en-us","version": 1,"scheduled_at": "2019-02-14T18:30:00.000Z"}).then(...).catch(...);
entry.unpublish(payload) ⇒ Promise

This method lets you unpublish an entry either immediately or schedule it to be unpublished automatically at a later date/time.

Kind: instance method of Entry

ParameterTypeDescription
payloadobjectPayload for the request.

Example

extension.stack.ContentType('contenttype_uid').Entry('bltsomething123').unpublish({"entry": {"environments": ["development"],"locales": ["en-us"]},"locale": "en-us","version": 1,"scheduled_at": "2019-02-14T18:30:00.000Z"}).then(...).catch(...);
entry.setWorkflowStage(payload) ⇒ Promise

This method allows you to either set a particular workflow stage or update the workflow stage details of an entry.

Kind: instance method of Entry

ParameterTypeDescription
payloadobjectPayload for the request.

Example

extension.stack.ContentType('contenttype_uid').Entry('bltsomething123').setWorkflowStage({"workflow": {"workflow_stage": {"comment": "Test Comment","due_date": "Thu Dec 01 2018","notify": false,"uid": "blt9f52a2cd5e0014fb","assigned_to": [{"uid": "blt296a22e28cc0c63c","name": "John Doe","email": "john.doe@contentstack.com"}],"assigned_by_roles": [{"uid": "blt5b74c24c7ae25d94","name": "Content Manager"}]}}}).then(...).catch(...);
entry.update(payload, [locale]) ⇒ Promise

This call allows you to update the entry content.

Kind: instance method of Entry

See: Update Entry

ParameterTypeDescription
payloadobjectPayload for the request.
[locale]stringPassing the ‘locale’ parameter will localize the entry in the specified locale.

Example

extension.stack.ContentType('contenttype_uid').Entry('bltsomething123').update({"entry": {"title": "example","url": "/example"}}).then(...).catch(...);
Entry.Query() ⇒ Query

This static method instantiates the query module for entries. To see the list of methods that can be used for querying entries, refer to the Query module.

Kind: static method of Entry

Example

letentryQuery=extension.stack.ContentType('content_type_uid').Entry.Query();entryQuery.where("field_uid": "10").limit(10).skip(10).find().then(...).catch(...);
Entry.create(payload) ⇒ Promise

This method creates a new entry.

Kind: static method of Entry

Returns: Promise - Required data if resolved successfully

Additional Resource: Learn more about [Creating an Entry](https://www.contentstack.com/docs/apis/content-management-api/#create-a-an-entry| Create Entry).

ParameterTypeDescription
payloadObjectData to create an entry.

Example

extension.stack.ContentType('content_type_uid').Entry.create({"entry": {"title": "example","url": "/example"}}).then(...).catch(...);

stack.Asset

Kind: instance class of Stack

See: Asset

.Asset

new this.Asset(uid)

An initializer is responsible for creating an Asset object.

ParameterTypeDescription
uidstringUID of the asset.

Example

extension.stack.Asset("asset_uid");

asset.only([key], values) ⇒ Asset

This method is used to show the selected fields of the assets in the result set.

Kind: instance method of Asset

ParameterTypeDefaultDescription
[key]StringBASESingle field of an asset
valuesArrayArray of fields to be shown in the result set

Example( Only with the field UID )

extension.stack.Asset("bltsomething123").only("title").fetch();

Example( Only with the field UID )

extension.stack.Asset("bltsomething123").only("BASE","title").fetch();

Example( Only with the field UIDs(array) )

extension.stack.Asset("bltsomething123").only(["title","description"]).fetch();

asset.except([key], values) ⇒ Asset

This method is used to hide the selected fields of the assets in the result set.

Kind: instance method of Asset

ParameterTypeDefaultDescription
[key]StringBASESingle field of an asset
valuesArrayArray of fields to be hidden in the result set

Example( .Except with the field UID )

extension.stack.Asset("bltsomething123").except("title").fetch();

Example( .Except with the field UID )

extension.stack.Asset("bltsomething123").except("BASE","title").fetch();

Example( .Except with the field UIDs(array) )

extension.stack.Asset("bltsomething123").except(["title","description"]).fetch();

asset.environment(environment_uid) ⇒ Asset

This method is used to set the environment name of which you want to retrieve the data.

Kind: instance method of Asset

ParameterTypeDescription
environment_uidStringUID/Name of environment

Example

extension.stack.Asset("bltsomething123").environment("development").fetch();

asset.addParam(key, value) ⇒ Asset

This method includes a query parameter in your query.

Kind: instance method of Asset

ParameterTypeDescription
environment_uidStringUID/Name of environment

Example

extension.stack.Asset("bltsomething123").environment("development").fetch();

asset.addQuery(key, value) ⇒ Asset

This method includes a query parameter in your query.

Kind: instance method of Asset

ParameterTypeDescription
keystringKey of the parameter
valuestringValue of the parameter

Example

extension.stack.Asset("uid").addQuery("key","value").fetch().then().catch();

asset.getReferences() ⇒ Promise

This method fetches the details of entries and the assets in which the specified asset is referenced.

Kind: instance method of Asset

Additional Resource: Learn more about [Asset References](https://www.contentstack.com/docs/apis/content-management-api/#get-all-references-of-asset| Asset References).

Example

extension.stack.Asset("uid").getReferences().then().catch();

asset.delete() ⇒ Promise

This method deletes an existing asset.

Kind: instance method of Asset

Additional Resource: Learn more about [Deleting an Asset](https://www.contentstack.com/docs/apis/content-management-api/#delete-an-asset| Delete Asset).

Example

extension.stack.Asset("uid").delete().then().catch();

asset.publish(payload, api_version="") ⇒ Promise

This method allows you to publish the asset either immediately or schedule the publish for a later date/time.

Kind: instance method of Asset

ParameterTypeDescription
payloadobjectPayload for the request.
api_versionstringSend api version in headers.(optional argument)

Example

extension.stack.Asset("bltsomething123").publish({asset: {locales: ["en-us"],environments: ["development"],},version: 1,scheduled_at: "2019-02-08T18:30:00.000Z",});

asset.unpublish(payload) ⇒ Promise

This method instantly unpublishes the asset and also gives you the provision to automatically unpublish the asset at a later date/time.

Kind: instance method of Asset

ParameterTypeDescription
payloadobjectPayload for the request.

Example

extension.stack.Asset("bltsomething123").unpublish({asset: {locales: ["en-us"],environments: ["development"],},version: 1,scheduled_at: "2019-02-08T18:30:00.000Z",});

Asset.Query() ⇒ Query

This static method instantiates the query module for assets. To see the list of methods that can be used for querying assets, refer to the Query module.

Kind: static method of Asset

Example

letassetQuery=extension.stack.Asset.Query();assetQuery.where("title": "main.js").limit(10).skip(10).find().then(...).catch(...);

Asset.getRteAssets() ⇒ Promise

This static method retrieves comprehensive information on all assets uploaded through the Rich Text Editor field.

Kind: static method of Asset

Asset.getAssetsOfSpecificTypes(assetType) ⇒ Promise

This static method retrieves assets that are either image or video files, based on the request query.

Kind: static method of Asset

ParameterTypeDescription
assetTypeStringType of asset to be received for e.g., ‘image/png’

stack.getData() ⇒ Object

This method returns the data of the current stack.

Kind: instance method of Stack

Returns: Object - Returns stack data.

stack.getContentType(uid, params) ⇒ Object

This API allows you to retrieve data of a content type of a stack using the Content Type API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with content type details.

ParameterTypeDescription
uidstringUID of the desired content type
paramsObjectOptional parameters for the GET call

stack.getContentTypes(query, params) ⇒ Object

This API allows you to retrieve data of a content type of a stack using the Content Types API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with details of the content type.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

stack.getEnvironment(name, params) ⇒ Object

This API allows you to retrieve environment details of a stack using the Environment API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with environment details.

ParameterTypeDescription
namestringName of the desired environment
paramsObjectOptional parameters for the GET call

stack.getEnvironments(query, params) ⇒ Object

This API allows you to retrieve details of environments of a stack using the Environments API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the environments.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

stack.getLocale(code, params) ⇒ Object

This API allows you to retrieve a locale of a stack using the Language API requests. Method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with locale details.

ParameterTypeDescription
codestringCode of the desired locale
paramsObjectOptional parameters for the GET call

stack.getLocales(query, params) ⇒ Object

This API allows you to retrieve the locales of a stack using the Languages API requests. Method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the locales.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

stack.getReleases(query, params) ⇒ Object

This API allows you to retrieve details of releases of a stack using the Releases API requests. Method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the releases.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

stack.getPublishes(query, params) ⇒ Object

This API allows you to retrieve details of publish queue of a stack using the Publish Queue API requests. Method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the publish queue.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

stack.search(queries: StackSearchQuery, apiKey?: string | null) => Promise<Object>

This API allows you to search for content in a stack. It uses the API used by the Contentstack Search Bar. By default, the current stack is searched. Method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the stacks in the organization.

ParameterTypeDescription
queriesObjectQueries for the GET call
apiKeystringOptional parameters to search stack of specific API key

StackSearchQuery

This is the type of the queries parameter of the search method.

StackSearchQuery{ type: "entries"|"assets"; skip?: number; limit?: number; include_publish_details?: boolean; include_unpublished?: boolean; include_workflow?: boolean; include_fields?: boolean; include_rules?: boolean; include_title_field_uid?: boolean; query?: AnyObject; search?: string; save_recent_search?: boolean; desc?: string;}

stack.getAllStacks(options: {orgUid = "", params = {}}): Promise<Object[]>

This API allows you to retrieve details of all the stacks of an organization using the Get all Stacks API requests. Method returns a Promise object.

Note: In order to fetch the stacks, you must have access to the stacks.

Kind: instance method of Stack

Returns: Object - A Promise object which will be resolved with details of the stacks in the organization.

ParameterTypeDescription
options.orgUidstringOptional parameter to change the organization
options.paramsObjectOptional parameters for the GET call

stack.getCurrentBranch() ⇒ BranchDetail | null

This API allows you to retrieve details of current branch of the stack, if available. If the Branches plan is not available, it will return null.

Note: Branch feature is plan based.

Kind: instance method of Stack

Returns: Object - An object which will be resolved with details of the current branch.

stack.getAllBranches() ⇒ BranchDetail[] | null

This API allows you to retrieve details of all the available branches in the stack. If the Branches plan is not available, it will return an empty array.

Note: Branch feature is plan based.

Kind: instance method of Stack

Returns: Array - An Array of object which will be resolved with details of all the branches.

BranchDetail

This is the interface of the branch returned by the stack.getCurrentBranch() and stack.getAllBranches() methods.

BranchDetail{ api_key: string; uid: string; source: string; alias: { uid: string;}[];}

stack.getVariantById(variant_uid) ⇒ Object

This API allows you to retrieve data of a single entry variant of a stack using the Variants API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with variant entry details.

ParameterTypeDescription
variant_uidstringvariant UID of desired entry

stack.getGlobalField(uid, params) ⇒ Object

This API allows you to retrieve data of a single global field of a stack using the Global Field API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with global field details.

ParameterTypeDescription
uidstringUID of the desired global field
paramsObjectOptional parameters for the GET call

stack.getGlobalFields(query, params) ⇒ Object

This API allows you to retrieve data of all global fields of a stack using the Global Fields API requests. This method returns a Promise object.

Kind: instance method of Stack

Returns: Object - A promise object which will be resolved with global field details.

ParameterTypeDescription
queryObjectQuery for the GET call
paramsObjectOptional parameters for the GET call

The Store Class used by an extension to store your data in localStorage.

Kind: global class

store.get(key) ⇒ Promise

It fetches the value of a key.

Kind: instance method of Store

ParameterTypeDescription
keystringKey of the stored data

Example

extension.store.get("key").then((value)=>console.log(value));// will log value for the given key

store.getAll() ⇒ Promise

It fetches an object with all the stored key-value pairs.

Kind: instance method of Store

Example

extension.store.getAll().then((obj)=>obj);

store.set(key, value) ⇒ Promise

It sets the value of a key

Kind: instance method of Store

ParameterTypeDescription
keystringKey of the stored data.
value*Data to be stored.

Example

extension.store.set("key","value").then((success)=>console.log(success));// will log 'true' when value is set

store.remove(key) ⇒ Promise

It removes the value of a key.

Kind: instance method of Store

ParameterTypeDescription
keystringKey of the data to be removed from the store

Example

extension.store.remove("key").then((success)=>console.log(success));// will log 'true' when value is removed

store.clear() ⇒ Promise

It clears all the stored data of an extension.

Kind: instance method of Store

Example

Example

extension.store.clear().then((success)=>console.log(success));// will log 'true' when values are cleared

Query

Creates an instance of the query

Kind: global class
Version: 2.2.0

query.lessThan ⇒ Query

This method provides only the entries with values less than the specified value for a field.

Kind: instance property of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare.

Example

extension.stack.ContentType("blog").lessThan("created_at","2015-06-22");

query.lessThanOrEqualTo ⇒ Query

This method provides the entries with values less than or equal to the specified value for a field.

Kind: instance property of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare

Example

extension.stack.ContentType("blog").lessThanOrEqualTo("created_at","2015-03-12");

query.only([key], values) ⇒ Query

This method is used to show the selected fields of an entry in the result set.

Kind: instance method of Query

ParameterTypeDefaultDescription
[key]StringBASESingle field of an entry
valuesArrayArray of fields to be shown in the result set

Example( Only with field UID )

extension.stack.ContentType("content_type_uid").Entry.Query().only("title").find();

Example( Only with field UID )

extension.stack.ContentType("content_type_uid").Entry.Query().only("BASE","title").find();

Example( Only with field UIDs(array) )

extension.stack.ContentType("content_type_uid").Entry.Query().only(["title","description"]).find();

query.except([key], values) ⇒ Query

This method is used to hide the selected fields of an entry in the result set.

Kind: instance method of Query

ParameterTypeDefaultDescription
[key]StringBASESingle field of an entry
valuesArrayArray of fields to be hidden in the result set

Example( Except with field uid )

extension.stack.ContentType("content_type_uid").Entry.Query().except("title").find();

Example( Except with field uid )

extension.stack.ContentType("content_type_uid").Entry.Query().except("BASE","title").find();

Example( Except with field uids(array) )

extension.stack.ContentType("content_type_uid").Entry.Query().except(["title","description"]).find();

query.addQuery(key, value) ⇒ Query

This method includes a query parameter in a query.

Kind: instance method of Query

ParameterTypeDescription
keystringKey of the parameter
valuestringValue of the parameter

Example

extension.stack.ContentType("content_type_uid").Entry.Query().addQuery("key","value").find().then().catch();

query.greaterThan(key, value) ⇒ Query

This method provides the entries with values greater than the specified value for a field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare

Example

extension.stack.ContentType("blog").greaterThan("created_at","2015-03-12");

query.greaterThanOrEqualTo(key, value) ⇒ Query

This method provides the entries with values greater than or equal to the specified value for a field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare

Example

extension.stack.ContentType("blog").greaterThanOrEqualTo("created_at","2015-06-22");

query.notEqualTo(key, value) ⇒ Query

This method provides the entries with values not equal to the specified value for a field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare

Example

extension.stack.ContentType("blog").notEqualTo("title","Demo");

query.containedIn(key, value) ⇒ Query

This method provides the entries with values matching the specified values for a field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*An array of values that are to be used to match or compare

Example

extension.stack.ContentType("blog").containedIn("title",["Demo","Welcome"]);

query.notContainedIn(key, value) ⇒ Query

This method provides the entries that do not contain values matching the specified values for a field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
valueArrayAn array of values that are to be used to match or compare

Example

extension.stack.ContentType("blog").notContainedIn("title",["Demo","Welcome"]);

query.exists(key) ⇒ Query

This method provides the entries that contain the field matching the specified field UID.

Kind: instance method of Query

ParameterTypeDescription
keyStringThe UID of the field

Example

extension.stack.ContentType("blog").exists("featured");

query.notExists(key) ⇒ Query

This method provides the entries that do not contain the field matching the specified field UID.

Kind: instance method of Query

ParameterTypeDescription
keyStringThe UID of the field

Example

extension.stack.ContentType("blog").notExists("featured");

query.ascending(key) ⇒ Query

This parameter sorts the entries in the ascending order on the basis of the value of the specified field.

Kind: instance method of Query

ParameterTypeDescription
keyStringField UID to be used for sorting.

Example

extension.stack.ContentType("blog").ascending("created_at");

query.descending(key) ⇒ Query

This method sorts the entries in the descending order on the basis of the specified field.

Kind: instance method of Query

ParameterTypeDescription
keyStringField UID to be used for sorting

Example

extension.stack.ContentType("blog").descending("created_at");

query.skip(skip) ⇒ Query

This method skips the specified number of entries.

Kind: instance method of Query

ParameterTypeDescription
skipNumberNumber of entries to be skipped

Example

extension.stack.ContentType("blog").skip(5);

query.limit(limit) ⇒ Query

This method limits the response by providing only the specified number of entries.

Kind: instance method of Query

ParameterTypeDescription
limitNumberMaximum number of entries to be returned in the result.

Example

extension.stack.ContentType("blog").limit(10);

query.or(Array) ⇒ Query

This method performs the OR operation on the specified query objects and provides only the matching entries.

Kind: instance method of Query

ParameterTypeDescription
Arrayobjectof query objects/raw queries to be taken into consideration

Example( OR with query instances)

letQuery1=extension.stack.ContentType("blog").Entry.Query().where("title","Demo");letQuery2=extension.stack.ContentType("blog").Entry.Query().lessThan("comments",10);letblogQuery=extension.stack.ContentType("blog").or(Query1,Query2);

Example( OR with query instances)

letQuery1=extension.stack.ContentType("blog").Entry.Query().where("title","Demo").getQuery();letQuery2=extension.stack.ContentType("blog").Entry.Query().lessThan("comments",10).getQuery();letblogQuery=extension.stack.ContentType("blog").or(Query1,Query2);

query.and(Array) ⇒ Query

This method performs the AND operation on the specified query objects and provides only the matching entries.

Kind: instance method of Query

ParameterTypeDescription
Arrayobjectof query objects/raw queries to be taken into consideration

Example( AND with raw queries)

letQuery1=extension.stack.ContentType("blog").Entry.Query().where("title","Demo");letQuery2=extension.stack.ContentType("blog").Entry.Query().lessThan("comments",10);letblogQuery=extension.stack.ContentType("blog").and(Query1,Query2);

Example( .and with raw queries)

letQuery1=extension.stack.ContentType("blog").Entry.Query().where("title","Demo").getQuery();letQuery2=extension.stack.ContentType("blog").Entry.Query().lessThan("comments",10).getQuery();letblogQuery=extension.stack.ContentType("blog").and(Query1,Query2);

query.addParam(key, value) ⇒ Query

This method includes a query parameter in a query.

Kind: instance method of Query

ParameterTypeDescription
keystringKey of the parameter
valuestringValue of the parameter

Example

extension.stack.ContentType("content_type_uid").Entry.Query().addParam("key","value").find().then().catch();

query.includeReference() ⇒ Query

This method is used to include the referenced entries from other content types.

Note: This method is only valid for querying Entry.

Kind: instance method of Query

Example( .includeReference with reference_field_uids as array )

stack.ContentType("contenttype_uid").Entry.Query().includeReference(["category","author"]).find();

Example( .includeReference with reference_field_uids )

stack.ContentType("contenttype_uid").Entry.Query().includeReference("category","author").find();

query.includeSchema() ⇒ Query

This method is used to include the schema of the current content type in the result set along with the entry/entries.

Note: This method is only valid for querying Entry.

Kind: instance method of Query

Example

extension.stack.ContentType("contenttype_uid").Entry.Query().includeSchema().find();

query.language(languageCode) ⇒ Query

This method is used to set the language code of which you want to retrieve the data.

Note: This method is only valid for querying Entry.

Kind: instance method of Query

ParameterTypeDescription
languageCodeStringLanguage code, for e.g. ‘en-us’, ‘ja-jp’, and so on

Example

extension.stack.ContentType("contenttype_uid").Entry.Query().language("en-us").find();

query.includeContentType() ⇒ Query

This method is used to include the current content type in the result set along with the entry(ies).

Note: This method is only valid for querying Entry.

Kind: instance method of Query

Example

extension.stack.ContentType("contenttype_uid").Entry.Query().includeContentType().find();

query.includeOwner() ⇒ Query

This method is used to include the owner of the entry(ies) in the result set.

Note: This method is only valid for querying Entry.

Kind: instance method of Query

Example

extension.stack.ContentType("contenttype_uid").Entry.Query().includeOwner().find();

query.environment(environment_uid) ⇒ Query

This method is used to set the environment name of which you want to retrieve the data.

Kind: instance method of Query

ParamTypeDescription
environment_uidStringUID/Name of environment.

Example

extension.stack.ContentType("contenttype_uid").Entry.Query().environment("development").find();

query.equalTo(key, value) ⇒ Query

This method provides only the entries containing field values that match the specified condition.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare

Example

extension.stack.ContentType("blog").where("title","Demo");

query.count() ⇒ Query

This method provides only the number of entries that match the specified filters.

Kind: instance method of Query

Example

extension.stack.ContentType("blog").count();

query.query(query) ⇒ Query

This method is used to set raw queries on the Query instance.

Kind: instance method of Query

ParameterTypeDescription
queryobjectRaw {json} queries to filter the entries in the result set.

query.tags(values) ⇒ Query

The 'tags' parameter allows you to specify an array of tags to search for objects.

Kind: instance method of Query

ParameterTypeDescription
valuesArrayTags

Example

extension.stack.ContentType("blog").tags(["technology","business"]);

query.includeCount() ⇒ Query

This method also includes the total number of entries returned in the response.

Kind: instance method of Query

Example

extension.stack.ContentType("blog").includeCount();

query.getQuery() ⇒ Query

This method provides raw{json} queries based on the filters applied on the Query object.

Kind: instance method of Query

Summary: returns Returns the raw query which can be used for further calls (.and/.or).

Example

extension.stack.ContentType("blog").where("title","Demo").getQuery();

query.regex(key, value, [options]) ⇒ Query

This method provides only the entries that match the regular expression for the specified field.

Kind: instance method of Query

ParameterTypeDescription
keyStringUID of the field
value*The value used to match or compare
[options]StringMatch or compare a value in the entry

Example( .regex without options)

letblogQuery=extension.stack.ContentType('blog').regex('title','^Demo')|

Example( .regex with options)

letblogQuery=extension.stack.ContentType('blog').regex('title','^Demo','i')|

query.search(value) ⇒ Query

This method is used to search data in entries.

Kind: instance method of Query

ParameterTypeDescription
valuestringValue to search in the entries.

Example

extension.stack.ContentType("blog").search("Welcome to demo");

query.find()

This method provides all the entries which satisfy the specified query.

Kind: instance method of Query

Example

letblogQuery=extension.stack.ContentType('blog').find()|

query.findOne()

This method provides a single entry from the resultant set.

Kind: instance method of Query

Example:

letblogQuery=extension.stack.ContentType('blog').findOne()|

Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Kind: global external

See: Promise

localStorage

localStorage is the read-only property that allows you to access a Storage object for the Document’s origin. The data that gets stored is saved across browser sessions.

Kind: global external

See: localStorage

JSON RTE Plugins

In this document, we will discuss the API requests that a JSON RTE Plugin can use to communicate with Contentstack.

Prerequisites

Structure of JSON Rich Text Editor

{ "type": "doc", "children": [ { "type": "p", "children": [ { "text": "Paragraph" } ] }, { "type": "h1", "children": [ { "text": "Heading One" } ] } ] }

In the JSON Rich Text Editor, the JSON structure is represented as a Node which consists of two types:

  1. Block Node
  2. Leaf Node

The editor content that is inside a Node of type doc acts as a root for the content. Where a Block node is a JSON structure with a “children” key in it. Whereas a Leaf node will just have “text” which may include formatting properties (mark) such as “bold”, “italic”, etc.

Mark: You'll see a mark used in below example which is nothing but a leaf property on how to render content.

For example:

{ "text": "I am Bold", "bold": true }

Here, bold is the mark or the formatting to be applied to the "I am Bold" text.

Block Leaf Image

Render Type

A Block node can be rendered in three different ways as follow:

  1. Block
  2. Inline
  3. Void

Block Types

Path

Path arrays are a list of indexes that describe a node's exact position.

Path

In the JSON Rich Text Editor, a Path has the following structure:

Number[]

For example, the path for doc is [0], paragraph is [0,0] from the above given example.

Point

Point objects refer to a specific location of text in the leaf node. Its path refers to the location of the node in the tree, and its offset refers to distance into the node's string of text.

Point

In the JSON Rich Text Editor, a Point has the following structure:

{path: Path,offset: Number}

Range

A Range is a set of start (anchor) and end (focus) points that specify a range in a JSON document.

png

The structure of a Range is as follows:

{anchor: Point,focus: Point}

Location

Location is one of the ways to specify the location in a JSON document. It could be a Path, Point, or Range.

Inclusion in your project

For JSON RTE Plugins, you will need to install @contentstack/app-sdk in your React project. You will also need to clone the boilerplate GitHub repository that contains the template needed to create a JSON RTE plugin.

Classes

RTEPlugin(plugin_id, callback)

This method allows you to create a JSON RTE plugin instance.

Kind: Instance property of the JSON RTE plugin

Returns: Object - Plugin Object

ParameterTypeDescription
plugin_idstringUnique ID of the plugin
configCallback(rte: IRteParam) => IConfigThis function receives an RTE instance as argument and it expects you to return a config object that includes details like title, icon, render, etc.

configCallback: (rte: IRteParam) => IConfig

IConfig: This user-defined object will have all the essential metadata for the plugin.

The following table contains the possible properties of IConfig:

KeyTypeDescription
titlestringIdentifier for the toolbar button
iconReactNodeIcon which will be used for buttons
display(‘toolbar’ | ‘hoveringToolbar’)[]Location of the plugin
elementType(‘inline’ | ‘void’ | ‘block’)[]Render type
renderReactNodeComponent to be rendered within the editor when corresponding plugin_uid appears in json.

rte: An instance which has all the essential functions required to interact with the JSON RTE.

Following are a list of helpful properties and methods of the JSON RTE instance.

Properties:

rte.ref: Returns the HTML reference of the JSON RTE.

rte.fieldConfig: Contains metadata about the JSON RTE field which can be specified in the content type builder page.

KeyDescriptionType
rich_text_typeType of JSON RTE'basic' | 'advance' | 'custom'
reference_toList of content type uid used in JSON RTE references.string[]
optionsArray of selected toolbar buttons ( available if rich_text_type is ‘custom’ )string[]
titleTitle of the fieldstring
uidUnique ID for the fieldstring
rte.getConfig: () => Object

Provides configuration which is defined while creating the plugin or while selecting a plugin in the content type builder page.

For example, if your plugin requires API Key or any other config parameters, then you can specify these configurations while creating a new plugin or you can specify field specific configurations from the content type builder page while selecting the plugin. These configurations can be accessed through the getConfig() method.

RTE Methods

These methods are part of the RTE instance and can be accessed as rte.methodName().

MethodDescriptionType
getPathRetrieves the path of the node(node:Node) => Path
setAttrsSets attributes for the node.
For Eg: These attributes can be
href for anchor plugin
width, src for image plugin.
(attrs:Object, options:Option) => void
Option: NodeOptions
isNodeOfTypeRetrieves a boolean value, whether the node at the current selection is of input type(type:string) => boolean
getNodeRetrieves node at given location(location:Location) => Node
getNodesRetrieves a generator of nodes which includes the location specified in options at default at current selection(options:Option) => Node[]
Option: NodeOptions
stringString value of JSON in given path(location:Location) => string
addMarkAdds mark to the text(key:string, val:any) => void
removeMarkRemoves mark from the text(key:string) => void
hasMarkChecks if the selected text has a mark(key:string) => boolean
insertTextInserts text at a given location(text:string, location: Location) => void
getTextGets text from a given location() => string
deleteTextDeletes text from selected range() => void
updateNodeUpdates nodes based on provided options(type:string,attrs:Object, options: Option) => void
Option: NodeOptions
unsetNodeConverts a node to a normal paragraph based on provided options(options: Option) => void
Option: NodeOptions
insertNodeInserts a node at a given location. Having select option true will select the node after insertion(node:Node, options?: Option) => void
Option: NodeOptions & { select?: boolean }
deleteNodeDeletes a node at a given location(options: Option) => void
Option: {at?: Location, distance?: number, unit?: 'character' | 'word' | 'line' | 'block'}
wrapNodeWraps node based on provided options with given node(node:Node, options: Option) => void
Option: NodeOptions
unWrapNodeUnwraps node based on provided options from the parent node(options: Option) => void
Option: NodeOptions
mergeNodesMerges nodes based on provided options(options: Option) => void
Option: NodeOptions
getEmbeddedItemsGets details of embedded items JSON RTE.() => Object
getVariableGets local variable(name: string) => any
setVariableSets a local variable(name: string, val:any) => void

rte.selection: Contains a set of methods to perform selection related tasks.

FunctionDescriptionType
getRetrieves current selection() => Range
setSets the selection to a given location(location: Location) => void
isSelectedIt is a React hook which returns true when the current node is selected.() => boolean
isFocusedIt is React hook which returns true when the current node is focused() => boolean
getEndRetrieves the end location of the editor() => Path
beforeRetrieves the prior location before current selection(location: Location, options: Option) => Location
Option: {distance?: number, unit?: 'offset' | 'character' | 'word' | 'line' | 'block'}
afterRetrieves the subsequent location after current selection(location: Location, options: Option) => Location
Option: {distance?: number, unit?: 'offset' | 'character' | 'word' | 'line' | 'block'}
isPointEqualChecks if two points are equal(point1: Point, point2: Point) => boolean
Node Options:

Functions that involve transformation or change have an options parameter which includes options specific to transform and general NodeOptions to specify which nodes in the document you can apply the transform function.

interfaceNodeOptions{at?: Location;match?: (node: Node,path: Location)=>boolean;}
  • The at option selects a Location in the editor. It defaults to the user's current selection.
  • The match option filters the set of nodes with a custom function.
Events function:

These are accessible methods of the RTE instance. Can be invoked like rte.{{event_name}}()

FunctionDescriptionArguments
isFocusedCheck if the editor is focused() => boolean
focusFocuses the editor() => boolean
blurBlurs the editor() => boolean

Plugin:

Editor Events
Plugin.on: (event_type, callback) => void
event_typeDescriptionCallback Arguments
keydownWhen keydown is performed({event: KeyboardEvent, rte: RTE}) => void
execWhen a button is clicked or triggered(rte: RTE) => void
deleteBackwardWhen backward deletion occurs({rte: RTE, preventDefault: Function, ...args:[unit:"character" | "word" | "line" | "block"]}) => void
deleteForwardWhen forward deletion occurs({rte: RTE, preventDefault: Function, ...args:[unit:"character" | "word" | "line" | "block"]}) => void
normalizeIt is used to normalize any dirty ( unwanted structure ) objects in the editor({rte: RTE, preventDefault: Function, ...args:[[node:Node, path:Path]]}) => void
insertTextInserts text in the current selection({rte: RTE, preventDefault: Function, ...args:[string]}) => void
changeWhen there is a change in the editor({rte: RTE, , preventDefault: Function}) => void
insertBreakWhen the enter key is pressed({rte: RTE, preventDefault: Function}) => void
Dropdown plugin
Plugin.addPlugins: (...Plugin) => void

The addPlugins method can help you group the plugins under a dropdown that shares the same theme. Also, the addPlugins method takes a list of plugins as input.

For example, the code for addPlugins is as follows:

constChooseAsset=RTE("choose-asset",()=>{/** Choose Asset Code */});constUploadAsset=RTE("upload-asset",()=>{/** Upload Asset Code */});constAsset=RTE("asset-picker",()=>{/** Asset Picker Code */});Asset.addPlugins(ChooseAsset,UploadAsset);

The output for a dropdown plugin in UI is as follows:

Metadata

Metadata is a piece of information that lets you describe or classify an asset/entry. You can manage your digital entities effectively and enable improved accessibility with additional metadata. This object manages all the CRUD operations you can perform with metadata, e.g., adding, updating, or deleting additional metadata.

Note: The Metadata feature allows users to update their asset metadata or entry metadata without incrementing the asset or entry version.

createMetadata(metadataConfig: IMetadataCreate)

IMetadataCreate{ entity_uid: string; type?: "asset"|"entry";// default: "asset" _content_type_uid?: string; locale?: string;[key: string]: any;// other fields you want to add}

This method adds new metadata for an asset or entry. It accepts metadata configuration as required arguments. This config contains basic details that you need to identify the metadata object and other data you need for your app.

retrieveMetadata(metadataConfig: IMetadataRetrieve)

IMetadateRetrieve{ uid: string;}

This method retrieves metadata for an asset or entry. It accepts metadata configuration as required arguments. This config contains basic details that you need to identify the metadata object you want to retrieve.

retrieveAllMetaData(metadataConfig: AnyObject)

You can use Get all Metadata to fetch the metadata information of all the entries/assets present in your stack.

updateMetadata(metadataConfig: IMetadataUpdate)

IMetadataUpdate{ uid: string;[key: string]: any;// other fields you want to update}

This method updates existing metadata for an asset or entry. It accepts metadata configuration as required arguments. This config contains basic details that you need to identify the metadata object and other data you want to update.

deleteMetadata(metadataConfig: IMetadataDelete)

IMetadateDelete{ uid: string;}

This method deletes existing metadata for an asset or entry. It accepts metadata configuration as required arguments. This config contains basic details that you need to identify the metadata object you want to delete.

Modal

The Modal class represents a modal dialog opened from the app within the Contentstack UI. This feature of the App SDK enables apps to open modal dialogues, providing an enhanced user experience.

Note: Starting from v1.6.0 of the App SDK, modals now open to take the full screen by default, without any additional user action.

setBackgroundElement(element: HTMLElement)

This method allows developers to specify a custom HTML element to be displayed in the background, in place of the app iframe when the modal is opened. By default, the App SDK automatically selects an element to be shown in the background. However, this method provides the flexibility to choose a different element if required.

Example

// JavaScriptContentstackAppSDK.init().then(asyncfunction(appSdk){// Set the background element to be shownappSdk.modal.setBackgroundElement(element);});

About

This repository holds the api reference of the Contentstack's app-sdk

Resources

License

Security policy

Stars

Watchers

Forks

close