PublishRules

View as Markdown

PublishRules

A publish rule requires approval before anyone publishes or unpublishes entries of chosen content types to an environment, in chosen locales. The PublishRules class manages publish rules through the Content Management API (CMA). Use this class to

  • create a publish rule for a workflow
  • list the publish rules of a stack, or read one rule
  • change the approvers, locales or content types of a rule
  • delete a rule

Call the publishRule method on stack.workflow() to get an object. To read the rules of one content type, use the getPublishRules method of the Workflow class.

Instance State

  • Call stack.workflow().publishRule() without a UID to work with the collection, for example create and fetchAll.
  • Call stack.workflow().publishRule('<PUBLISH_RULE_UID>') to work with one rule, for example fetch and update.
  • Each form has only its own methods. A method of the other form is undefined, and calling it throws TypeError.

The Method Index below lists the full set for each form.

Warning publishRule('') returns the collection form, because the SDK treats an empty string as no UID. Check the UID before you build the object.

Class-Level Notes

Publish rule objects from responses.

Branch scope.

  • A publish rule applies to the branches in its branches key. Set it in the body of create, or change it with update.

Headers.

Rate limiting and retry.

  • This SDK automatically retries on 429 with configurable delay and attempt limits.

Additional Resource For more information on the retry options and their defaults, refer to the Contentstack documentation.

Capability Matrix

CapabilitySupportedNotes / Alternative
Reach publish rules from stack directlyNoCall stack.workflow().publishRule().
Approve or reject a publish requestNoUse the publishRequest method of the Entry class.

Method Index

Work with the publish rule collection. Available on stack.workflow().publishRule().

Method NameReturnsDescription
createThe new publish rule.Creates a publish rule.
fetchAllThe publish rules of the stack.Lists the publish rules.

Work with one publish rule. Available on stack.workflow().publishRule('<PUBLISH_RULE_UID>').

Method NameReturnsDescription
fetchThe requested publish rule.Reads one publish rule.
updateThe updated publish rule.Saves changes to the publish rule.
deleteThe API response with a notice.Deletes the publish rule.

Set request headers. Available on both forms.

Method NameReturnsDescription
addHeaderThe same publish rule object, for chaining.Adds one request header.
addHeaderDictThe same publish rule object, for chaining.Adds several request headers.
removeHeaderThe same publish rule object, for chaining.Removes one request header.

Class-Level Snippet

The snippet below lists the publish rules of a stack and prints the environment and actions of each rule.

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rules = await stack.workflow().publishRule().fetchAll({ include_count: true })
  console.log(rules.count)
  for (const rule of rules.items) {
    console.log(rule.uid, rule.environment, rule.actions)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Methods

Each method of the PublishRules class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to the requests that this publish rule object sends.

NameTypeDescription
key (required)string

Header name, for example x-request-id.

Default: Not applicable
value (required)string

Header value to send.

Default: Not applicable

Returns: PublishRules. The same publish rule object, for chaining.

Validation

  • There is no client-side validation. A null or undefined key leaves the headers unchanged, and addHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeader sends no request.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The PublishRules objects that create, fetch and fetchAll return start with the headers of this object.
  • A key that the object already holds gets the new value.

Example

Basic usage: tag the requests of one publish rule object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.workflow().publishRule('<PUBLISH_RULE_UID>').addHeader('x-request-id', 'docs-123')
console.log(target.stackHeaders['x-request-id'])

addHeaderDict

addHeaderDict adds several headers at once to the requests that this publish rule object sends.

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

Returns: PublishRules. The same publish rule object, for chaining.

Validation

  • There is no client-side validation. A null value, or a value that is not an object, leaves the headers unchanged, and addHeaderDict returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeaderDict sends no request.
  • addHeaderDict copies every key of headerDict into the header map of this object. A key that the object already holds gets the new value.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The PublishRules objects that create, fetch and fetchAll return start with the headers of this object.

Example

Basic usage: add a request ID and a trace ID

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.workflow().publishRule('<PUBLISH_RULE_UID>').addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'trace-456' })
console.log(target.stackHeaders['x-request-id'], target.stackHeaders['x-trace-id'])

create

create creates a publish rule, which requires approval before anyone publishes or unpublishes entries of the chosen content types.

NameTypeDescription
data (required){ publishing_rule: PublishRulesData }

Request body, with the rule under the publishing_rule key.

Default: Not applicable
data.publishing_rule.workflow (required)string

UID of the workflow that the rule belongs to.

Default: Not applicable
data.publishing_rule.actionsstring[]

Actions the rule covers, for example publish.

Default: API default
data.publishing_rule.content_typesstring[]

Content type UIDs, or $all.

Default: API default
data.publishing_rule.localesstring[]

Locale codes that the rule applies to.

Default: API default
data.publishing_rule.environmentstring

UID of the environment that the rule applies to.

Default: API default
data.publishing_rule.approversobject

Users and roles who approve, as users and roles arrays.

Default: API default
data.publishing_rule.workflow_stagestring

UID of the workflow stage that the rule applies at.

Default: API default
data.publishing_rule.disable_approver_publishingboolean

The SDK sends it as given in the rule.

Default: API default
data.publishing_rule.branchesstring[]

Branch UIDs that the rule applies to.

Default: API default
paramobject

Query parameters, sent as given.

Default: undefined (sends no extra query parameters)

Returns: Promise<PublishRules>. The new publish rule.

Validation

  • There is no client-side validation. create sends data as given and does not check its keys.
  • create exists only on stack.workflow().publishRule(). On publishRule('<PUBLISH_RULE_UID>') it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends POST /v3/workflows/publishing_rules with data as the JSON body and param as query parameters, as Create publish rules describes.
  • The SDK does not wrap data. Put the rule under the publishing_rule key yourself.
  • Resolves to a PublishRules object that the SDK builds from the publishing_rule key of the response, with fetch, update and delete.

Example

Basic usage: require approval to publish every content type to one environment

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const data = {
  publishing_rule: {
    workflow: '<WORKFLOW_UID>',
    actions: ['publish'],
    content_types: ['$all'],
    locales: ['<LOCALE>'],
    environment: '<ENVIRONMENT>',
    approvers: { users: ['<USER_UID>'], roles: [] }
  }
}

try {
  const rule = await stack.workflow().publishRule().create(data)
  console.log(rule.uid)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: a rule for one workflow stage and two branches

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const data = {
  publishing_rule: {
    workflow: '<WORKFLOW_UID>',
    actions: ['publish', 'unpublish'],
    content_types: ['<CONTENT_TYPE_UID>'],
    locales: ['<LOCALE>'],
    environment: '<ENVIRONMENT>',
    approvers: { users: [], roles: ['<ROLE_UID>'] },
    workflow_stage: '<WORKFLOW_STAGE_UID>',
    disable_approver_publishing: false,
    branches: ['main', '<BRANCH>']
  }
}

try {
  // The second argument holds query parameters. The API lists none for this request.
  const rule = await stack.workflow().publishRule().create(data, {})
  console.log(rule.uid, rule.workflow_stage)
} catch (error) {
  console.error(error.errorMessage)
}

delete

delete deletes the publish rule whose UID you passed to stack.workflow().publishRule('<PUBLISH_RULE_UID>').

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<Response>. The API response with a notice.

Warning Deleting a publish rule removes it permanently, and entries it covered no longer need that approval to publish. You cannot undo this. Create the rule again with the create method if you need it.

Validation

  • There is no client-side validation.
  • delete exists only on publishRule('<PUBLISH_RULE_UID>') and on the PublishRules objects that requests return. On publishRule() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends DELETE /v3/workflows/publishing_rules/{rule_uid} with every key of param as a query parameter, as Delete publish rules describes. The API reference lists no query parameters for this request.
  • Resolves to the response body as a plain object, with the API message in notice.

Example

Basic usage: delete a publish rule

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').delete()
  console.log(response.notice)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  // delete sends every key of the object as a query parameter. The API lists none for this request.
  const response = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').delete({})
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

fetch

fetch retrieves the publish rule whose UID you passed to stack.workflow().publishRule('<PUBLISH_RULE_UID>').

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<PublishRules>. The requested publish rule.

Validation

  • There is no client-side validation.
  • fetch exists only on publishRule('<PUBLISH_RULE_UID>'). On publishRule() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends GET /v3/workflows/publishing_rules/{rule_uid} with every key of param as a query parameter, as Get a single publish rule describes. The API reference lists no query parameters for this request.
  • Resolves to a new PublishRules object that the SDK builds from the publishing_rule key of the response, with fetch, update and delete.

Example

Basic usage: read one publish rule

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rule = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').fetch()
  console.log(rule.uid, rule.actions, rule.environment, rule.approvers)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  // fetch sends every key of the object as a query parameter. The API lists none for this request.
  const rule = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').fetch({})
  console.log(rule.uid)
} catch (error) {
  console.error(error.errorMessage)
}

fetchAll

fetchAll lists the publish rules of the stack, optionally for some content types only.

NameTypeDescription
paramobject

Query parameters for the list request.

Default: {}
param.content_typesstring

Comma-separated content type UIDs to filter by.

Default: API default
param.limitnumber

Maximum number of rules to return.

Default: API default
param.skipnumber

Number of rules to skip.

Default: API default
param.include_countboolean

Adds the total rule count to the response.

Default: API default

Returns: Promise<ContentstackCollection>. The publish rules of the stack.

Validation

  • There is no client-side validation.
  • fetchAll exists only on stack.workflow().publishRule(). On publishRule('<PUBLISH_RULE_UID>') it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends GET /v3/workflows/publishing_rules with every key of param as a query parameter, as Get all publish rules describes.
  • Pass content_types as one comma-separated string, for example 'blog_post,author', not as an array.
  • Resolves to a collection whose items are PublishRules objects, each with fetch, update and delete. With include_count: true, the collection also has count.
  • The client does not page through results. Use limit and skip to read more pages.

Example

Basic usage: list the publish rules of a stack

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rules = await stack.workflow().publishRule().fetchAll()
  for (const rule of rules.items) {
    console.log(rule.uid, rule.environment, rule.actions)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: list the rules of one content type, with the total count

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rules = await stack.workflow().publishRule().fetchAll({
    content_types: '<CONTENT_TYPE_UID>',
    limit: 10,
    skip: 0,
    include_count: true
  })
  console.log(rules.count, rules.items.length)
} catch (error) {
  console.error(error.errorMessage)
}

removeHeader

removeHeader removes one header from the requests that this publish rule object sends.

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

Returns: PublishRules. The same publish rule object, for chaining.

Validation

  • There is no client-side validation. A null or undefined key, or a key that the object does not hold, leaves the headers unchanged, and removeHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. removeHeader sends no request.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The PublishRules objects that create, fetch and fetchAll return start with the headers of this object.
  • removeHeader can remove a header that the object inherited from the stack, such as branch. The stack and its other objects keep that header.
  • Do not remove api_key. Without it, the API cannot tell which stack the request is for.

Example

Basic usage: drop a header that you added earlier

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.workflow().publishRule('<PUBLISH_RULE_UID>')
  .addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'trace-456' })
  .removeHeader('x-trace-id')
console.log('x-trace-id' in target.stackHeaders) // false

update

update saves the changes that you made to the properties of this publish rule object, such as its approvers or locales.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<PublishRules>. The updated publish rule.

Validation

  • There is no client-side validation.
  • update exists only on publishRule('<PUBLISH_RULE_UID>') and on the PublishRules objects that requests return. On publishRule() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Sends PUT /v3/workflows/publishing_rules/{rule_uid} with every key of param as a query parameter, as Update publish rules describes.
  • The body is { publishing_rule: { ... } }, built from the properties of this object. The SDK leaves out uid, created_at, created_by, updated_at, updated_by, deleted_at, org_uid, api_key and its own internal properties.
  • Call fetch first and change the result. An object from publishRule('<PUBLISH_RULE_UID>') holds no rule details, so update on it sends an empty rule.
  • Resolves to a new PublishRules object that the SDK builds from the publishing_rule key of the response.

Example

Basic usage: add a locale to a publish rule

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rule = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').fetch()
  rule.locales = [...rule.locales, '<LOCALE>']
  const updated = await rule.update()
  console.log(updated.locales)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: change the approvers and pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const rule = await stack.workflow().publishRule('<PUBLISH_RULE_UID>').fetch()
  rule.approvers = { users: ['<USER_UID>'], roles: ['<ROLE_UID>'] }
  // update sends every key of the object as a query parameter. The API lists none for this request.
  const updated = await rule.update({})
  console.log(updated.approvers)
} catch (error) {
  console.error(error.errorMessage)
}