Role
Role
A role is a set of permissions that applies to every user who holds it. The Role class manages the roles of one stack through the Content Management API (CMA). Use this class to
- list and search the roles of a stack
- create a role with its rules, for example a role that can edit entries but not publish them
- read, change or delete one role
Call the role method of the Stack class to get an object.
Instance State
- Call stack.role() without a UID to work with the collection, for example create and query.
- Call stack.role('<ROLE_UID>') to work with one role, for example fetch and update.
- Each form has only its own request methods. fetch is undefined on stack.role(), and create is undefined on stack.role('<ROLE_UID>'), so calling the wrong one throws TypeError.
- The Role objects in the result of the Organization roles method carry no stack API key, so they have no fetch, update or delete. Use stack.role('<ROLE_UID>') to change a role.
Warning stack.role('') 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
Headers.
- Every request sends the headers of this object, which start as a copy of the stack headers. Change them with addHeader, addHeaderDict and removeHeader.
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
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Change a system role | No | The API rejects changes to the roles that every stack starts with |
| Change only the name of a role without its rules | No | update sends every property of the object. Fetch the role with its rules first |
| List the roles of an organization | No | Use the Organization roles method |
Method Index
Work with the collection. Available on stack.role().
| Method Name | Returns | Description |
|---|---|---|
| create | The new role. | Creates a role in the stack. |
| fetchAll | The roles of the stack. | Lists every role of the stack. |
| query | A query for roles, sent when you call find(), findOne() or count(). | Builds a filtered role query. |
Work with one role. Methods available on stack.role('<ROLE_UID>'):
| Method Name | Returns | Description |
|---|---|---|
| fetch | The requested role. | Retrieves one role. |
| update | The updated role. | Saves changes to one role. |
| delete | The API response with a notice. | Deletes one role. |
Set request headers. Available on both forms.
| Method Name | Returns | Description |
|---|---|---|
| addHeader | The same role object, for chaining. | Adds one request header. |
| addHeaderDict | The same role object, for chaining. | Adds several request headers. |
| removeHeader | The same role object, for chaining. | Removes one request header. |
Class-Level Snippet
The snippet below reads a role with its rules, renames it, and saves the change.
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const role = await stack.role('<ROLE_UID>').fetch({ include_rules: true, include_permissions: true })
role.name = 'Content Reviewer'
const updated = await role.update()
console.log(updated.uid, updated.name)
} 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 Role class has its own section below, with its parameters, validation rules, behavior, and examples.
addHeader
addHeader adds one header to every request that this role object sends.
| Name | Type | Description |
|---|---|---|
| key (required) | string | Header name, for example x-request-id. |
| value (required) | string | Header value to send. |
Returns: Role. The same role 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 from the stack. 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 objects that those methods return carry the same headers.
- query() copies the headers at the moment you call it. Change the headers first, then call query().
- A key that the object already holds gets the new value.
Example
Basic usage: tag the requests of one role object
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const role = stack.role('<ROLE_UID>').addHeader('x-request-id', 'docs-123')
// Every request this object sends from now on carries the header
console.log(role.stackHeaders['x-request-id'])addHeaderDict
addHeaderDict adds several headers at once to every request that this role object sends.
| Name | Type | Description |
|---|---|---|
| headerDict (required) | object | Header names and values to add. |
Returns: Role. The same role 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.
- The first header change on this object copies the headers that it inherited from the stack. 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 objects that those methods return carry the same headers.
- query() copies the headers at the moment you call it. Change the headers first, then call query().
- addHeaderDict merges headerDict into the headers of the object. A key that the object already holds gets the new value.
Example
Basic usage: add two tracing headers
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const role = stack.role().addHeaderDict({
'x-request-id': 'docs-123',
'x-trace-id': 'trace-456'
})
console.log(role.stackHeaders['x-request-id'], role.stackHeaders['x-trace-id'])create
create adds a new role to the stack.
| Name | Type | Description |
|---|---|---|
| data (required) | { role: RoleData } | Request body, with the role under the role key. |
| data.role.name (required) | string | Display name of the role. |
| data.role.description | string | Short text about what the role allows. |
| data.role.rules (required) | object[] | Permission rules, one per module. |
| param | object | Query parameters, sent as given. |
Returns: Promise<Role>. The new role.
Validation
- There is no client-side validation. create sends data as given and does not check its keys.
- create exists only on stack.role(). On stack.role('<ROLE_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/roles with data as the JSON body, as Create a role describes.
- The SDK does not wrap data. Put the role under the role key yourself.
- Each rule names a module, the items it covers, and an acl object of allowed actions. For example, { module: 'environment', environments: ['$all'], acl: { read: true } } allows read access to every environment.
- Resolves to a Role object that the SDK builds from the role key of the response, with fetch, update and delete.
Example
Basic usage: create a role that can edit content but not publish it
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const data = {
role: {
name: 'docs-test-content-editor',
description: 'Creates and edits content, cannot publish',
rules: [
{
module: 'content_type',
content_types: ['$all'],
acl: { read: true, sub_acl: { read: true, create: true, update: true, delete: false, publish: false } }
},
{ module: 'asset', assets: ['$all'], acl: { read: true, update: true, publish: false, delete: false } },
{ module: 'environment', environments: ['$all'], acl: { read: true } },
{ module: 'locale', locales: ['<LOCALE>'], acl: { read: true } }
]
}
}
try {
const role = await stack.role().create(data)
console.log(role.uid, role.name)
} 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 with the request
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const data = {
role: {
name: 'docs-test-environment-reader',
description: 'Reads every environment',
rules: [{ module: 'environment', environments: ['$all'], acl: { read: true } }]
}
}
// Query parameters to send with the request
const param = {}
try {
const role = await stack.role().create(data, param)
console.log(role.uid)
} catch (error) {
console.error(error.errorMessage)
}delete
delete removes the role whose UID you passed to stack.role('<ROLE_UID>') from the stack.
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
Returns: Promise<Response>. The API response with a notice.
Warning A successful delete removes the role and its rules, and you cannot undo it. Call fetch with include_rules: true first to keep a copy of its settings.
Validation
- There is no client-side validation.
- delete exists only on stack.role('<ROLE_UID>') and on the Role objects that fetch, create, fetchAll and query return. On stack.role() 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/roles/{role_uid} with every key of param as a query parameter, as Delete role describes.
- Resolves to the response body, which carries notice. When the API answers with an empty body, it resolves to { status, statusText } instead.
Example
Basic usage: delete one role
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.role('<ROLE_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 with the request
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
// Query parameters to send with the request
const param = {}
try {
const response = await stack.role('<ROLE_UID>').delete(param)
console.log(response.notice)
} catch (error) {
console.error(error.errorMessage)
}fetch
fetch retrieves the role whose UID you passed to stack.role('<ROLE_UID>').
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
| param.include_permissions | boolean | Adds the permissions of the role. |
| param.include_rules | boolean | Adds the rules of the role. |
Returns: Promise<Role>. The requested role.
Validation
- There is no client-side validation.
- fetch exists only on stack.role('<ROLE_UID>'). On stack.role() 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/roles/{role_uid} with every key of param as a query parameter, as Get a single role describes.
- Resolves to a new Role object that holds the role fields, with fetch, update and delete. The object you called fetch on does not change.
- Fetch with include_rules: true before you call update, so the object holds the current rules when update sends it back.
Example
Basic usage: read one role
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const role = await stack.role('<ROLE_UID>').fetch()
console.log(role.uid, role.name, role.description)
} 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: read a role with its rules and permissions
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const role = await stack.role('<ROLE_UID>').fetch({ include_permissions: true, include_rules: true })
for (const rule of role.rules) {
console.log(rule.module, rule.acl)
}
} catch (error) {
console.error(error.errorMessage)
}fetchAll
fetchAll retrieves every role of the stack.
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
| param.include_permissions | boolean | Adds the permissions of each role. |
| param.include_rules | boolean | Adds the rules of each role. |
Returns: Promise<ContentstackCollection>. The roles of the stack.
Validation
- There is no client-side validation.
- fetchAll exists only on stack.role(). On stack.role('<ROLE_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/roles with every key of param as a query parameter, as Get all roles describes.
- Resolves to a ContentstackCollection. Its items array holds one Role object per role, each with fetch, update and delete.
- To filter the roles, use the query method instead.
Example
Basic usage: list the roles 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 roles = await stack.role().fetchAll()
for (const role of roles.items) {
console.log(role.uid, role.name)
}
} 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: include the rules and permissions of each role
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const roles = await stack.role().fetchAll({ include_permissions: true, include_rules: true })
for (const role of roles.items) {
console.log(role.name, role.rules.length)
}
} catch (error) {
console.error(error.errorMessage)
}query
query builds a request for the roles that match a condition. It sends nothing until you call a method of the returned query.
| Name | Type | Description |
|---|---|---|
| params | object | Query parameters for the request. |
| params.query | object | Condition on role fields, sent as JSON. |
| params.include_permissions | boolean | Adds the permissions of each role. |
| params.include_rules | boolean | Adds the rules of each role. |
Returns: Query. A query for roles, sent when you call find(), findOne() or count().
Validation
- There is no client-side validation.
- query exists only on stack.role(). On stack.role('<ROLE_UID>') it is undefined, and calling it throws TypeError.
- An invalid value surfaces as a rejected promise from the request method you call next.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Client-side only. query copies the headers of this object and params, and returns a Query object.
- find and findOne send GET /v3/roles and resolve to Role objects. count resolves to the response body, which holds the number of matching roles.
- The SDK sends params.query as query=<JSON>, as Get all roles describes. It sends every other key of params as a query parameter.
Example
Basic usage: find a role by name
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const result = await stack.role().query({ query: { name: 'Developer' } }).find()
for (const role of result.items) {
console.log(role.uid, role.name)
}
} 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: find one role with its rules and permissions
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const result = await stack.role()
.query({ query: { name: 'Developer' }, include_permissions: true, include_rules: true })
.findOne()
console.log(result.items[0].rules)
} catch (error) {
console.error(error.errorMessage)
}removeHeader
removeHeader removes one header from the requests that this role object sends.
| Name | Type | Description |
|---|---|---|
| key (required) | string | Name of the header to remove. |
Returns: Role. The same role 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 from the stack. 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 objects that those methods return carry the same headers.
- query() copies the headers at the moment you call it. Change the headers first, then call query().
- 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 role = stack.role('<ROLE_UID>')
.addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'trace-456' })
.removeHeader('x-trace-id')
console.log('x-trace-id' in role.stackHeaders) // falseupdate
update saves the current properties of the role object to the role.
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
Returns: Promise<Role>. The updated role.
Validation
- There is no client-side validation.
- update exists only on stack.role('<ROLE_UID>') and on the Role objects that fetch, create, fetchAll and query return. On stack.role() 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/roles/{role_uid} with every key of param as a query parameter, as Update role describes.
- The body is { role: { ... } } with every data property of the object. The SDK leaves out uid, urlPath, stackHeaders, api_key, org_uid and the created_*, updated_* and deleted_at fields.
- update sends what the object holds, not only what you changed. On stack.role('<ROLE_UID>') without a fetch, the body holds only the properties you set. Call fetch with include_rules: true first, then change the properties and call update.
- The API rejects changes to the system roles that every stack starts with.
- Resolves to a new Role object that the SDK builds from the response.
Example
Basic usage: rename a role and change its description
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const role = await stack.role('<ROLE_UID>').fetch({ include_rules: true, include_permissions: true })
role.name = 'Content Reviewer'
role.description = 'Reviews content before it goes live'
const updated = await role.update()
console.log(updated.name, updated.description)
} 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: add read access to every environment 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 role = await stack.role('<ROLE_UID>').fetch({ include_rules: true, include_permissions: true })
role.rules.push({ module: 'environment', environments: ['$all'], acl: { read: true } })
// Query parameters to send with the request
const param = {}
const updated = await role.update(param)
console.log(updated.rules.length)
} catch (error) {
console.error(error.errorMessage)
}