|
| 1 | +import PubNub, { PubNubError } from '../lib/types'; |
| 2 | + |
| 3 | +const pubnub = new PubNub({ |
| 4 | + publishKey: 'demo', |
| 5 | + subscribeKey: 'demo', |
| 6 | + userId: 'myUniqueUserId', |
| 7 | +}); |
| 8 | + |
| 9 | +// snippet.iterativelyUpdateExistingMetadata |
| 10 | +const channel = 'team.red'; |
| 11 | +const name = 'Red Team'; |
| 12 | +const description = 'The channel for Red team.'; |
| 13 | +const customField = { visible: 'team' }; |
| 14 | + |
| 15 | +// Function to set and then update channel metadata |
| 16 | +try { |
| 17 | + const response = await pubnub.objects.setChannelMetadata({ |
| 18 | + channel: channel, |
| 19 | + data: { |
| 20 | + name: name, |
| 21 | + description: description, |
| 22 | + custom: customField, |
| 23 | + }, |
| 24 | + }); |
| 25 | + console.log('The channel has been created with name and description.\n'); |
| 26 | + |
| 27 | + // Fetch current object with custom fields |
| 28 | + const currentObjectResponse = await pubnub.objects.getChannelMetadata({ |
| 29 | + channel: channel, |
| 30 | + include: { |
| 31 | + customFields: true, |
| 32 | + }, |
| 33 | + }); |
| 34 | + const currentObject = currentObjectResponse.data; |
| 35 | + |
| 36 | + // Initialize the custom field object |
| 37 | + const custom = currentObject.custom || {}; |
| 38 | + |
| 39 | + // Add or update the field |
| 40 | + custom['edit'] = 'admin'; |
| 41 | + |
| 42 | + // Writing the updated object back to the server |
| 43 | + const setResponse = await pubnub.objects.setChannelMetadata({ |
| 44 | + channel: channel, |
| 45 | + data: { |
| 46 | + name: currentObject.name || '', |
| 47 | + description: currentObject.description || '', |
| 48 | + custom: custom, |
| 49 | + }, |
| 50 | + }); |
| 51 | + console.log('Object has been updated', setResponse); |
| 52 | +} catch (error) { |
| 53 | + console.error( |
| 54 | + `Set channel metadata error: ${error}.${ |
| 55 | + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' |
| 56 | + }`, |
| 57 | + ); |
| 58 | +} |
| 59 | +// snippet.end |
0 commit comments