PubNub FunctionsPubNub Module

The PubNub module provides PubNub client API methods.

 
  1. The maximum recursion limit you can do is 3 - hops from one Function to another, using publish or fire, you can execute a maximum of three Functions.
  2. The combined maximum number within a single Function execution of KV store operations, XHRs, publish and fire is 3.

The PubNub module is made available via the following require statement:

const pubnub = require('pubnub');

To publish a message to PubNub Subscribers and Functions, use the publish() method.

Usage

ParameterTypeRequiredDescription
message ObjectYesJavaScript object to be sent to PubNub.
channel String YesPubNub destination channel.
pubnub.publish({
    "channel": "hello_universe",
    "message": request.message
}).then((publishResponse) => {
    console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
});
 
Payload that is published requires a valid JSON, strings will not trigger Function.

To publish a message to Functions only, use the fire() method.

Usage

ParameterTypeRequiredDescription
messageObjectYesJavaScript object to be sent to PubNub.
channel String YesPubNub destination channel.
pubnub.fire({
    "channel": "hello_universe",
    "message": request.message
}).then((publishResponse) => {
    console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
});

To send a signal to PubNub Subscribers and Functions, use the signal() method.

By default, signals are limited to a message payload size of 30 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Usage

ParameterTypeRequiredDescription
message ObjectYesJavaScript object to be sent to PubNub.
channel String YesPubNub destination channel.
pubnub.signal({
    "channel": "hello_universe",
    "message": request.message // must be smaller than 30 bytes
}).then((signalResponse) => {
    console.log(`Signal Status: ${signalResponse[0]}:${signalResponse[1]} with TT ${signalResponse[2]}`);
});
 
Payload that is published via signal requires a valid JSON, strings will not trigger Function.

At present, the main use case for Functions is to construct the URL and integrate with external services; for example, for image moderation, or for logging. To upload and download files, you need to use a PubNub client SDK.

Retrieve the list of files uploaded to a channel.

Usage

listFiles accepts a single argument, a Javascript Object with the following properties:

ParameterTypeRequiredDefaultDescription
channelStringYesRetrieve list of files for this channel.
limitNumberOptional100Number of files to return.
nextStringOptionalString token to get the next batch of files.
const pubnub = require('pubnub');

return pubnub.listFiles({
    channel: 'my_channel',
    limit: 2,
    next: '10rX15WW7pyYsbwPY2h3ZlPfP1vSFl_3M6rCappuuCSULLIQb3MWOOba7xouJDxxs8yS9Ql6mxdz-1FmMdeiUE53GPMjNLmrUtefZdhoaswVwat7Z0Q6YzXi4FQYclt7pW_nQlOaC-vzaGSaeSB4QeQS2vlmjyiDVFYPQvSz6g39X7__1H73-XgogHZqqI-jnWMonp2fpgcQ',
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});

Returns

Returns a promise that resolves to an Object with the following format:

{
  status: number,
  data: Array<{
    name: string,
    id: string,
    size: number,
    created: string
  }>,
  next: string,
  count: number,
}

For example:

{
  status: 200,
  data: [
      {
        name: 'cat_picture.jpg',
        id: '0936618c-94f9-4e96-bd9c-aa4fd8719c28',
        size: 31,
        created: '2020-08-13T19:05:30Z'
      },
      {
        name: 'my_other_file.jpg',
        id: '2afb0f85-8eb3-43bf-84f9-5b4c7e031f8f',
        size: 23,
        created: '2020-08-13T19:07:22Z'
      },
  ],
  next: "1NrsIonxYtGgsxNA3_Klt6jxt235cJUKY3hRNXkRP1TlHrzCSPj0yhysBgb04dRtwtkeR7lxcKyq-Y-CU7wxB1Tplf-NaW3mFYrzV5DDhGK7WEuT3FIBpg8RfA2rIScBhLJ-3Jaqthf9SKKU2fJzkPdPgwdz7yJvrfWrmsyXzZblbprUXl_HWaUKv4aE7_wP-91Nz_xpwM84",
  count: 2,
}

Get a file's direct download URL. This method doesn't make any API calls, and won't decrypt an encrypted file.

Usage

getFileUrl accepts a single argument, a Javascript Object with the following properties:

ParameterTypeRequiredDescription
channelStringYesChannel that the file was sent to.
idStringYesThe file's unique identifier.
nameStringYesName of the file.
const pubnub = require('pubnub');

const url = pubnub.getFileUrl({
    channel: 'my_channel',
    id: '12345678-1234-5678-123456789012',
    name: 'cat_picture.jpg',
});

console.log(url);

Returns

Returns a string with the following format:

'https://ps.pndsn.com/v1/files/my-subkey/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg'

Deletes a file from the specified channel.

Usage

deleteFile accepts a single argument, a Javascript Object with the following properties:

ParameterTypeRequiredDescription
channelStringYesChannel that the file was sent to.
idStringYesThe file's unique identifier.
nameStringYesName of the file.
const pubnub = require('pubnub');

return pubnub.deleteFile({
    channel: 'my_channel',
    id: '12345678-1234-5678-123456789012',
    name: 'cat_picture.jpg' ,
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});

Returns

Returns a promise that resolves to an Object with the following format:

{
  status: 200,
}

Manually publish information about a previously uploaded file.

Usage

publishFile accepts a single argument, a Javascript Object with the following properties:

ParameterTypeRequiredDefaultDescription
channelStringYesChannel on which to send the file message
fileIdStringYesThe file's unique identifier
fileNameStringYesName of the file.
messageObjectOptionalMessage to attach to the file. The message can be any value that can be JSON stringified.
storeInHistoryBooleanOptionaltrueWhether published file messages should be stored in the channel's history.
If storeInHistory isn't specified, then the history configuration on the key is used.
ttlNumberOptionalHow long the message should be stored in the channel's history, in hours.
If not specified, defaults to the key set's retention value.
metaObjectOptionalAdditional metadata published with the message.
const pubnub = require('pubnub');

return pubnub.publishFile({
    channel: 'my_channel',
    fileId: '12345678-1234-5678-123456789012',
    fileName: 'cat_picture.jpg',
    message: {
        someField: 'someValue',
    },
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});

Returns

Returns a promise that resolves to an Object with the following format:

[ 1, "Sent", "15973568884237770" ]

Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

To fetch Here Now use the hereNow() method.

Usage

ParameterTypeRequiredDescription
channels ArrayOptionalchannels is an Array which specifies the channels to return occupancy results.
channelGroups ArrayOptionalchannelGroups is an Array which specifies the channelGroup to return occupancy results.
includeUUIDs Boolean OptionalSetting includeUUIDs to false disables the return of uuids.
includeState BooleanOptionalSetting includeState to true enables the return of subscriber state information.
pubnub.hereNow({ 
    channels: ["ch1"], 
    channelGroups : ["cg1"], 
    includeUUIDs: true,
    includeState: true 
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

To fetch Where Now use the whereNow() method.

Usage

ParameterTypeRequiredDescription
uuid String Optionaluuid specifies the uuid to return channel list for.
pubnub.whereNow({ 
    uuid: "uuid"
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To fetch Global Here Now use the hereNow() method.

Usage

ParameterTypeRequiredDescription
includeUUIDs BooleanOptionalSetting includeUUIDs to false disables the return of uuids.
includeState BooleanOptionalSetting includeState to true enables the return of subscriber state information.
pubnub.hereNow({
    includeUUIDs: true, 
    includeState: true 
}).then((response) => { 
    console.log(response)
}).catch((error) => { 
    // handle error 
});

To fetch Set State use the setState() method.

Usage

ParameterTypeRequiredDescription
channelsArrayOptionalSpecifies the channels to get the state. Either channels or channelGroups should be provided.
channelGroupsArrayOptionalSpecifies the channelGroups to get the state. Either channels or channelGroups should be provided.
state ObjectOptionalstate is a JSON object of key/value pairs with supported data-types of int, float and string. Nesting of key/values is not permitted and key names beginning with prefix pn are reserved.
uuidStringOptionaluuid to set the current state.
pubnub.setState({ 
    channels: ['ch1'],
    channelGroups: ['cg1'],
    state: newState,
    uuid: "uuid" 
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

To fetch Set State use the getState() method.

Usage

ParameterTypeRequiredDescription
uuidStringOptionaluuid is the subscriber uuid to get the current state.
channelsArrayOptionalSpecifies the channels to get the state. Either channels or channelGroups should be provided.
channelGroups ArrayOptionalSpecifies the channelGroups to get the state. Either channels or channelGroups should be provided.
pubnub.getState({ 
    uuid: "uuid", 
    channels: ['ch1'], 
    channelGroups: ['cg1'] 
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

Requires Access Manager add-on XRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

To Grant Permissions use the grant() method.

Usage

ParameterTypeRequiredDescription
channels Array Specifying either channels or channelGroups is mandatory.channels is an Array which specifies the channels to grant permissions to.
channelGroups ArraySpecifying either channels or channelGroups is mandatory.channelGroups is an Array which specifies the channelGroup to grant permissions to.
authKeysArray OptionalSetting which specifies the authKeys to grant permissions to.
ttl Number Yesttl is the Number which specifies the Time in minutes for which granted permissions are valid.
read Boolean Yesread permissions are granted by setting to true.
write Boolean Yeswrite permissions are granted by setting to true.
manageBooleanYesmanage permissions are granted by setting to true.
pubnub.grant({
    channels: [ch1, ch2],
    channelGroups: [cg1, cg2],
    authKeys: [key1, key2],
    ttl: 12313,
    read: true,
    write: true,
    manage: true
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

To Grant channel and object permissions use the grantToken() method.

Usage

ParameterTypeRequiredDefaultsDescription
resourcesObjectSpecifying either resources or patterns is mandatorySet permissions by resource.
patternsObjectSpecifying either resources or patterns is mandatorySet permissions matching pattern.
ttlNumberOptional0Time to live for permission to be valid.
metaObjectOptionalCustom metadata included in token.
pubnub.grantToken({
    resources : {
        users : {
            user1 : {
                create : true,
            },
        },
        spaces : {
            space1 : {
                read : true,
            },
        },
        channels : {
            myChannel : {
                manage : true,
                delete : true,
            },
        },
        groups : {
            myGroup : {
                write : true,
            },
        },
    },
    patterns : {
        users : {
            '.*' : {
                manage : true,
                write : true,
            },
        },
        spaces : {
            '.*' : {
                delete : true,
            },
        },
        channels : {
            '^topic-[0-9a-f]*$' : {
                read : true,
                delete : true,
            },
        },
        groups : {
            '^:group-topic-*$' : {
                write : true,
            },
        },
    },
    ttl : 1440,
    meta : {
        foo : 'bar',
    },
}).then((token) => {
    console.log(token);
});

Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

To add channels to a channel group use channelGroups.addChannels().

  200 channels can be added to the channel group per API call.

Usage

ParameterTypeRequiredDescription
channelsArrayYeschannels is an Array, specifies channels to be added to a channelGroup.
channelGroup StringYeschannelGroup is a String, it specifies the channelGroup to add channels.
pubnub.channelGroups.addChannels({
    channels: ['ch1', 'ch2'],
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To list all the channels of the channel group use channelGroups.listChannels().

Usage

ParameterTypeRequiredDescription
channelGroup StringYeschannelGroup is a String, specifies the channelGroup to list the channel(s).
pubnub.channelGroups.listChannels({
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To remove the channels from the channel group use channelGroups.removeChannels().

Usage

ParameterTypeRequiredDescription
channelsArrayYeschannels is an Array, specifies channels to remove from the channelGroup.
channelGroup StringYeschannelGroup is a String, specifies the channelGroup to remove the channels.
pubnub.channelGroups.removeChannels({
    channels: ['ch1'],
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To remove the channel group use channelGroups.deleteGroup().

Usage

ParameterTypeRequiredDescription
channelGroup StringYeschannelGroup is a String, specifies the channelGroup to remove.
pubnub.channelGroups.deleteGroup({
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

To fetch History use the history() method.

Usage

ParameterTypeRequiredDescription
channel StringYesSpecifies channel to return history messages from.
reverse Boolean Optional

Setting to true will traverse the time line in reverse starting with the oldest message first.


If both start and end arguments are provided, reverse is ignored and messages are returned starting with the newest message.

count Number OptionalSpecifies the number of historical messages to return.
stringifiedTimeTokenBooleanOptionalIf stringifiedTimeToken is specified as true, the SDK will return timetoken values as a strings instead of integers. Usage of setting is encouraged in javascript environments which perform round-up/down on large integers.
startStringOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
endStringOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
export default (request) => {
    var pubnub = require('pubnub');

    return pubnub.history({
        'channel' : 'my_channel',
        'count' : 3,
        'stringifiedTimeToken' : true,
        'reverse' : true,
    }).then((response) => {
        console.log("startTT", response.startTimeToken);
        console.log("endTT", response.endTimeToken);
        response['messages'].forEach((value, index) => { 
            console.log("message:", value.entry, "timetoken:", value.timetoken);
        });
        return request.ok();
    });
};

To fetch History from multiple channels use the fetchMessages() method.

Usage

ParameterTypeRequiredDescription
channels ArrayYesSpecifies channels to return history messages from.
count Number OptionalSpecifies the number of historical messages to return per channel.
start String OptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
end String OptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
stringifiedTimeTokenBooleanOptionalIf stringifiedTimeToken is specified as true, the SDK will return timetoken values as a strings instead of integers.
pubnub.fetchMessages({
    'channels' : ['my_channel', 'my_other_channel'],
    'count' : 8,
    'start' : '15343325214676133',
    'end' : '15343325004275466',
    'stringifiedTimeToken' : true,
}).then((status, response) => {
    console.log(status);
    console.log(response);
});

To delete messages from the history use the deleteMessages() method.

 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.

Requires Initialization with secret key.

Usage

ParameterTypeRequiredDescription
channelStringYesSpecifies channel messages to be deleted from history.
startStringOptionalTime token delimiting the start of time slice (inclusive) to delete messages from.
endStringOptionalTime token delimiting the end of time slice (exclusive) to delete messages from.
pubnub.deleteMessages({
    'channel' : 'my_channel',
    'start': '15088506076921021',
    'end': '15088532035597390',
}).then((result) => {
    console.log(result);
});

Specifies the number of historical messages to return per channel. The count returned is the number of messages in history with a timetoken value greater than the passed value in the channelTimetokens parameter.

Usage

ParameterTypeRequiredDescription
channelsArrayYesThe channels to fetch the message count.
channelTimetokensArrayYesList of timetokens, in order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the function returns a PNStatus with an error flag.
pubnub.messageCounts({
    'channels' : ['my_channel', 'my_other_channel'],
    'channelTimetokens' : ['my_timetoken', 'my_other_timetoken'],
}).then((status, results) => {
    console.log(status);
    console.log(results);
});

Requires Mobile Push Notifications add-on XRequires that you enable the Mobile Push Notifications for your key. Refer to the following page for details on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.

To enable push notifications on provided set of channels use push.addChannels().

Usage

ParameterTypeRequiredDescription
channelsArrayYesSpecifies channel to associate with push notifications.
deviceStringYesThe device id to associate with push notifications.
pushGateway StringYesapns, mpns or gcm.
pubnub.push.addChannels({
    channels: ['my_channel', 'my_other_channel'],
    device: 'nice_device',
    pushGateway: 'apns'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To request for all channels on which push notification has been enabled use push.listChannels().

Usage

ParameterTypeRequiredDescription
deviceStringYesThe device id to associate with push notifications.
pushGateway StringYesapns, mpns or gcm.
pubnub.push.listChannels({
    device: 'nice_device',
    pushGateway: 'apns'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To disable push notifications on provided set of channels use push.removeChannels().

Usage

ParameterTypeRequiredDescription
channelsArrayYesSpecifies channel to associate with push notifications.
deviceStringYesThe device id to associate with push notifications.
pushGateway StringYesapns, mpns or gcm.
pubnub.push.removeChannels({
    channels: ['my_channel', 'my_other_channel'],
    device: 'nice_device',
    pushGateway: 'apns'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

To disable push notifications from all channels which is registered with specified pushToken use push.deleteDevice().

Usage

ParameterTypeRequiredDescription
deviceStringYesThe device id to associate with push notifications.
pushGateway StringYesapns, mpns or gcm.
pubnub.push.deleteDevice({
    device: 'nice_device',
    pushGateway: 'apns'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});

Returns a paginated list of UUID Metadata objects, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
includeObjectOptionalInclude additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
filterStringOptional Expression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllUUIDMetadata({
        limit: 1,
        include: {
            customFields: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch uuid metadata');
    });
};

Response

{
   "status" : 200,
   "data" : [
      {
         "name" : "my-name",
         "updated" : "2020-07-16T21:10:38.770048Z",
         "id" : "my-uuid",
         "email" : "me@email.com",
         "custom" : {
            "foo" : "bar"
         },
         "externalId" : null,
         "eTag" : "AePWsMnEl9m23wE",
         "profileUrl" : null
      }
   ],
   "next" : "Mg",
}

Other Examples

To get next page of the results.

export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllUUIDMetadata({
        limit: 1,
        include: {
            customFields: true,
        },
        page: {
            next: "Mg", // from previous response
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch uuid metadata');
    });
};

Response

{
  "status": 200
  "data": [
    {
      "created": "2020-03-10T18:45:49.460388Z",
      "eTag": "Ad+6yqHMr6TYxgE",
      "email": null,
      "externalId": null,
      "id": "my-other-uuid",
      "name": "my-other-name",
      "profileUrl": null,
      "updated": "2020-03-10T18:45:49.460388Z"
    }
  ],
  "next": "MQ",
  "prev": "Mg",
}

Returns metadata for the specified UUID, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
uuidStringYesUnique uuid identifier.
includeObjectOptionalSpecifies whether to include the uuid's custom data field.
  customFieldsBooleanOptionaltrueWhether to fetch custom fields.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getUUIDMetadata({
      uuid: 'my-uuid',
      include: {
        customFields: false,
      },
    })
    .then((resp) => {
      console.log(resp);
      return event.ok('Fetched UUID metadata successfully.');
    })
    .catch((err) => {
      console.log(err);
      return event.abort('Failed to fetch UUID metadata');
    });
};

Response

{
   "status" : 200,
   "data" : {
      "email" : "me@email.com",
      "profileUrl" : null,
      "externalId" : null,
      "updated" : "2020-07-16T21:10:38.770048Z",
      "name" : "my-name",
      "eTag" : "AePWsMnEl9m23wE",
      "id" : "my-uuid"
   }
}

Set metadata for a UUID in the database, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
uuidStringYesUnique uuid identifier.
dataObjectYesObject with uuid metadata to set.
  nameStringOptionalDisplay name for the uuid, maximum 200 characters.
  externalIdStringOptionaluuid's identifier in an external system.
  profileUrlStringOptionalThe URL of the uuid's profile picture.
  emailStringOptionalThe uuid's email address, maximum 80 characters.
  customObjectOptionalJSON object of key-value pairs with supported data types.
Values must be scalar only; arrays or objects are not supported.
includeObjectOptionalInclude additional fields in the response.
  customFieldsBooleanOptionaltrueWhether to fetch custom fields.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setUUIDMetadata({
        uuid: 'my-uuid',
        data: {
            name: 'my-name',
            email: 'me@email.com',
            custom: {
                foo: 'bar',
            },
        },
        include: {
            customFields: false,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set UUID metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set UUID metadata.');
    });
};

Response

{
  "status" : 200,
  "data" : {
    "email" : "me@email.com",
    "profileUrl" : null,
    "externalId" : null,
    "updated" : "2020-07-16T21:10:38.770048Z",
    "name" : "my-name",
    "eTag" : "AePWsMnEl9m23wE",
    "id" : "my-uuid"
  }
}

Removes the metadata from a specified UUID.

Usage

ParameterTypeRequiredDescription
uuidStringYesUnique uuid identifier.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeUUIDMetadata({
        uuid: 'my-uuid',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed UUID successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove UUID metadata');
    });
};

Response

{
  "status": 200,
  "data": null
}

Returns a paginated list of Channel Metadata objects, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
includeObjectOptionalInclude additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllChannelMetadata({
        limit: 1,
        include: {
            totalCount: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};

Response

{
   "status" : 200,
   "data" : [
      {
         "name" : "channel-name",
         "description" : "What a great channel",
         "updated" : "2020-07-16T21:18:12.156794Z",
         "eTag" : "AeWFs+b3rMH4Dw",
         "id" : "my-channel"
      }
   ],
   "totalCount" : 2,
   "next" : "MQ"
}

Other Examples

To get next page of the results.

export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllChannelMetadata({
        limit: 1,
        page: {
            next: "MQ", // from previous response
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};

Response

{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:19:28.735177Z",
      "eTag" : "AeDH5/ixi/7lZw",
      "id" : "my-other-channel",
      "description" : "What another great channel",
      "name" : "other-channel-name"
    }
  ],
  "prev" : "MQ",
  "next" : "Mg"
}

Returns metadata for the specified Channel, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesUnique channel identifier.
includeObjectOptionalSpecifies whether to include the channel's custom data field.
  customFieldsBooleanOptionaltrueWhether to fetch custom fields.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getChannelMetadata({
        channel: 'my-channel',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};

Response

{
  "status" : 200,
  "data" : {
    "description" : "What a great channel",
    "eTag" : "AeWFs+b3rMH4Dw",
    "id" : "my-channel",
    "updated" : "2020-07-16T21:18:12.156794Z",
    "custom" : {
       "foo" : "bar"
    },
    "name" : "channel-name"
  }
}

Set metadata for a Channel in the database, optionally including the custom data object for each.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesUnique channel identifier.
dataObjectYesObject with channel metadata to set.
  nameStringOptionalName of the channel.
  descriptionStringOptionalDescription of the channel.
  customObjectOptionalJSON object of key-value pairs with supported data types.
Values must be scalar only; arrays or objects are not supported.
includeObjectOptionalInclude additional fields in the response.
  customFieldsBooleanOptionaltrueWhether to fetch custom fields.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setChannelMetadata({
        channel: 'my-channel',
        data: {
            name: 'channel-name',
            description: 'What a great channel',
            custom: {
                foo: 'bar',
            },
        },
        include: {
            customFields: false,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set channel metadata.');
    });
};

Response

{
  "status" : 200,
  "data" : {
    "eTag" : "AeWFs+b3rMH4Dw",
    "id" : "my-channel",
    "name" : "channel-name",
    "description" : "What a great channel",
    "updated" : "2020-07-16T21:18:12.156794Z"
  }
}

Removes the metadata from a specified channel.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesUnique channel identifier.
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeChannelMetadata({
        channel: 'my-channel',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed channel successfully');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove channel metadata');
    });
};

Response

{
  "data": null,
  "status": 200
}

The method returns a list of channel memberships for a user. This method doesn't return a user's subscriptions.

Usage

ParameterTypeRequiredDefaultsDescription
uuidStringYesUUID whose memberships you wish to retrieve.
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  channelFieldsBooleanOptionalfalseWhether to include fields for channel metadata.
  customChannelFieldsBooleanOptionalfalseWhether to include custom fields for channel metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getMemberships({
        uuid: "my-uuid",
        limit: 2,
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch memberships');
    });
}

Response

{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:28:58.702287Z",
      "channel" : {
        "id" : "my-channel"
      },
      "eTag" : "AY39mJKK//C0VA"
    },
    {
      "eTag" : "AY39mJKK//C0VA",
      "updated" : "2020-07-16T21:28:21.992673Z",
      "channel" : {
        "id" : "my-other-channel"
      }
    }
  ],
  "next" : "Mg"
}

Set channel memberships for a UUID.

Usage

ParameterTypeRequiredDefaultsDescription
uuidStringYesUUID whose memberships you wish to set.
channelsArrayYesArray of channels to set membership.
Array can contain strings (channel-name only) or objects (which can include custom data).
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  channelFieldsBooleanOptionalfalseWhether to include fields for channel metadata.
  customChannelFieldsBooleanOptionalfalseWhether to include custom fields for channel metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setMemberships({
        uuid: "my-uuid",
        channels: [
            "my-channel",
            { id: "my-other-channel", custom: { hello: "world" } },
        ],
        include: {
            channelFields: true,
            customChannelFields: true,
            customFields: true,
            totalCount: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set memberships');
    });
}

Response

{
  "status" : 200,
  "data" : [
    {
      "channel" : {
        "id" : "my-channel"
      },
      "eTag" : "AY39mJKK//C0VA",
      "custom" : null,
      "updated" : "2020-07-16T21:28:58.702287Z"
    },
    {
      "updated" : "2020-07-16T21:28:58.693461Z",
      "custom" : {
        "hello" : "world"
      },
      "channel" : {
        "updated" : "2020-07-16T21:19:28.735177Z",
        "name" : "other-channel-name",
        "custom" : {
          "foo" : "bar"
        },
        "eTag" : "AeDH5/ixi/7lZw",
        "id" : "my-other-channel",
        "description" : "What another great channel"
      },
      "eTag" : "AbGV6rSh8LS/eg"
    }
  ],
  "next" : "NA",
  "totalCount" : 2
}

Remove channel memberships for a UUID.

Usage

ParameterTypeRequiredDefaultsDescription
uuidStringYesUUID from which to remove memberships.
channelsArrayYesArray of channels to remove from uuid memberships.
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  channelFieldsBooleanOptionalfalseWhether to include fields for channel metadata.
  customChannelFieldsBooleanOptionalfalseWhether to include custom fields for channel metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeMemberships({
        uuid: "my-uuid",
        channels: [ "my-channel", "my-other-channel" ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove memberships');
    });
}

Response

{
  "status": 200,
  "data": []
}

The method returns a list of members in a channel. The list will include user metadata for members that have additional metadata stored in the database.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel for which to retrieve members.
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  UUIDFieldsBooleanOptionalfalseWhether to include fields for uuid metadata.
  customUUIDFieldsBooleanOptionalfalseWhether to include custom fields for uuid metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getChannelMembers({
        channel: "my-channel",
        include: {
            UUIDFields: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch members');
    });
}

Response

{
  "status" : 200,
  "next" : "Mg",
  "data" : [
    {
      "eTag" : "AbGV6rSh8LS/eg",
      "uuid" : {
        "id" : "my-other-uuid"
      },
      "updated" : "2020-07-16T21:40:48.367305Z"
    },
    {
      "eTag" : "AY39mJKK//C0VA",
      "uuid" : {
        "profileUrl" : null,
        "eTag" : "AePWsMnEl9m23wE",
        "externalId" : null,
        "name" : "my-name",
        "id" : "my-uuid",
        "email" : "me@email.com",
        "updated" : "2020-07-16T21:44:27.504433Z"
      },
      "updated" : "2020-07-16T21:40:48.357234Z"
    }
  ]
}

This method sets members in a channel.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel for which to set members.
uuidsArrayYesArray of uuids to set as members. Array can contain strings (uuid-name only) or objects (which can include custom data).
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  UUIDFieldsBooleanOptionalfalseWhether to include fields for uuid metadata.
  customUUIDFieldsBooleanOptionalfalseWhether to include custom fields for uuid metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated.
Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setChannelMembers({
        channel: "my-channel",
        uuids: [
            "my-uuid",
            { id: "my-other-uuid", custom: { hello: "world" } },
        ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set members');
    });
}

Response

{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:40:48.367305Z",
      "eTag" : "AbGV6rSh8LS/eg",
      "uuid" : {
        "id" : "my-other-uuid"
      }
    },
    {
      "uuid" : {
        "id" : "my-uuid"
      },
      "eTag" : "AY39mJKK//C0VA",
      "updated" : "2020-07-16T21:40:48.357234Z"
    }
  ],
  "next" : "Mg"
}

Remove members from a Channel.

Usage

ParameterTypeRequiredDefaultsDescription
channelStringYesChannel from which to remove members.
uuidsArrayYesArray of uuids to remove from channel members.
includeObjectOptionalSpecifies whether to include additional fields in the response.
  customFieldsBooleanOptionalfalseWhether to fetch custom fields.
  UUIDFieldsBooleanOptionalfalseWhether to include fields for uuid metadata.
  customUUIDFieldsBooleanOptionalfalseWhether to include custom fields for uuid metadata.
  totalCountBooleanOptionalfalseWhether to include totalCount in response.
limitNumberOptional100Maximum number of results to return per page.
pageObjectOptionalUse for pagination.
  nextStringOptionalPreviously-returned cursor bookmark for fetching the next page.
  prevStringOptionalPreviously-returned cursor bookmark for fetching the previous page.
Ignored if you also supply the next parameter.
filterStringOptionalExpression used to filter the results. Only objects whose properties satisfy the given expression are returned.
The filter language is defined here.
sortObjectOptionalKey-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated. Sort directions are asc (ascending), desc (descending). For example: { name: 'asc' }
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeChannelMembers({
        channel: "my-channel",
        uuids: [ "my-uuid", "my-other-uuid" ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove members');
    });
}

Response

{
  "status": 200,
  "data": []
}

Add an action on a published message.

Usage

ParameterTypeRequiredDescription
channelStringYesName of channel which stores the message for which action should be added.
messageTimetokenStringYesTimetoken of message for which action should be added.
actionHashYesMessage action information.
action.typeStringYesWhat feature this message action represents.
action.valueStringYesValue which should be stored along with message action.
uuidStringYesThe uuid associated with the action.
pubnub.addMessageAction({
    channel: 'channel1'
    messageTimetoken: '15610547826970040',
    action: {
        type: 'reaction',
        value: 'smiley_face',
    },
    uuid: 'uuid'
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

Remove a peviously added action on a published message.

Usage

ParameterTypeRequiredDescription
channelStringYesName of channel which store message for which action should be removed.
messageTimetokenStringYesTimetoken of message for which action should be removed.
actionTimetokenStringYesAction addition timetoken.
uuidStringYesThe uuid associated with the action.
pubnub.removeMessageAction({
    channel: 'channel1'
    messageTimetoken: '15610547826970040',
    actionTimetoken: '15610547826970040',
    uuid: 'uuid'
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

Get a list of message actions in a channel.

Usage

ParameterTypeRequiredDescription
channelStringYesName of channel from which list of messages actions should be retrieved.
startStringOptionalMessage action timetoken denoting the start of the range requested.
Return values will be less than start.
endStringOptionalMessage action timetoken denoting the end of the range requested.
Return values will be greater than or equal to end.
limitNumberOptionalNumber of message actions to return in response.
pubnub.getMessageActions({
    channel: 'channel1',
    start: '15610547826970041',
    end: '15610547826970040',
    limit: 100,
}).then((response) => { 
    console.log(response) 
}).catch((error) => { 
    // handle error 
});

To request the current PubNub server time (timetoken), use the time() method.

pubnub.time().then((timetoken) => {
    console.log(timetoken);
});
 
PubNub Functions provides a rich set of tools, and this documentation does not cover all of the potential situations you may encounter. If you need help with a situation not covered by the documentation, please contact PubNub Support.