Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs-snippets/basic-usage/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,19 @@ const pubnubConfig = new PubNub({
});

// snippet.end

// snippet.setUserIdBasicUsage
pubnub.setUserId('myUniqueUserId');
// snippet.end

// snippet.getUserIdBasicUsage
const currentUserId = pubnub.getUserId();
// snippet.end

// snippet.getAuthKeyBasicUsage
const currentAuthKey = pubnub.getAuthKey();
// snippet.end

// snippet.destroyBasicUsage
pubnub.destroy();
// snippet.end
38 changes: 38 additions & 0 deletions docs-snippets/publish-subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,44 @@ try {
}
// snippet.end

// snippet.publishMinimal
const { timetoken } = await pubnub.publish({
channel: 'my_channel',
message: { text: 'Hello' },
});

console.log(timetoken); // "17918851187695440" (a string)
// snippet.end

// snippet.publishHandleErrors
try {
await pubnub.publish({
channel: 'my_channel',
message: { text: 'Hello' },
});
} catch (e) {
const status = (e as PubNubError).status;

if (status?.category === 'PNValidationErrorCategory') {
console.error('The call is invalid:', status.message);
} else if (status?.category === 'PNAccessDeniedCategory') {
console.error('403: the token or authKey has no write permission on the channel');
} else if (status?.category === 'PNNetworkIssuesCategory') {
console.error('The network is unreachable. Retry the publish yourself.');
} else {
console.error(status?.category, status?.statusCode, status?.errorData);
}
}
// snippet.end

// snippet.publishFalsyMessage
// message: 0 is rejected with "Missing 'message'", so wrap the value
await pubnub.publish({
channel: 'my_channel',
message: { value: 0 },
});
// snippet.end

// snippet.publishSuccessfull
const response = await pubnub.publish({
message: 'hello world!',
Expand Down
21 changes: 21 additions & 0 deletions docs-snippets/quickstart-commands.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/bin/sh
# Shell commands for the JavaScript quickstarts. This file is not run as a script.
# Each command group is embedded on its own through the snippet ids below.

# snippet.quickstartInstallPackage
npm install pubnub
# snippet.end

# snippet.quickstartNodeInstall
mkdir pubnub-quickstart
cd pubnub-quickstart
npm install pubnub
# snippet.end

# snippet.quickstartNodeRun
node index.mjs
# snippet.end

# snippet.quickstartCloneSource
git clone https://github.com/pubnub/javascript
# snippet.end
39 changes: 39 additions & 0 deletions docs-snippets/quickstart-node.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import PubNub from 'pubnub';

const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});

pubnub.addListener({
message: (event) => {
console.log(`Received on ${event.channel}: ${event.message}`);
},
status: (event) => {
if (event.category === 'PNConnectedCategory') {
console.log('Connected to PubNub');
}
},
});

// Create a channel entity
const channel = pubnub.channel('hello_world');

// Create a subscription
const subscription = channel.subscription({
receivePresenceEvents: true, // to receive presence events
});

// Subscribe
subscription.subscribe();

try {
const result = await pubnub.publish({
channel: 'hello_world',
message: 'Hello, world!',
});
console.log(`Published, timetoken: ${result.timetoken}`);
} catch (error) {
console.error(`Publish failed: ${error}`);
}
38 changes: 38 additions & 0 deletions docs-snippets/quickstart-node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import PubNub from '../lib/types';

// The Node.js quickstart runs as an ES module (index.mjs), so the import line comes from
// docs-snippets/import-pubnub.ts (importPubNub) and the initialization comes from
// docs-snippets/getting-started.ts (gettingStartedInitPubnub and gettingStartedCreateSubscription).
// The import above only lets the compiler check the snippets below.
// The runnable file that combines them all is docs-snippets/quickstart-node.mjs.

const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});

// snippet.quickstartNodeListeners
pubnub.addListener({
message: (event) => {
console.log(`Received on ${event.channel}: ${event.message}`);
},
status: (event) => {
if (event.category === 'PNConnectedCategory') {
console.log('Connected to PubNub');
}
},
});
// snippet.end

// snippet.quickstartNodePublish
try {
const result = await pubnub.publish({
channel: 'hello_world',
message: 'Hello, world!',
});
console.log(`Published, timetoken: ${result.timetoken}`);
} catch (error) {
console.error(`Publish failed: ${error}`);
}
// snippet.end
52 changes: 52 additions & 0 deletions docs-snippets/quickstart-react-app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { useEffect, useState } from 'react';
import PubNub from 'pubnub';

// Create the client once, outside the component, so re-renders reuse it
const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});

export default function App() {
const [messages, setMessages] = useState<string[]>([]);

useEffect(() => {
const subscription = pubnub.channel('hello_world').subscription();

subscription.onMessage = (event) => {
setMessages((previous) => [...previous, `${event.publisher}: ${event.message}`]);
};
subscription.subscribe();

// Runs on unmount, and before React re-runs the effect in development (StrictMode)
return () => {
subscription.unsubscribe();
};
}, []);

const [text, setText] = useState('');

const send = async () => {
if (!text.trim()) return;

try {
await pubnub.publish({ channel: 'hello_world', message: text });
setText('');
} catch (error) {
console.error(`Publish failed: ${error}`);
}
};

return (
<div>
<ul>
{messages.map((message, index) => (
<li key={index}>{message}</li>
))}
</ul>
<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Type a message" />
<button onClick={send}>Send</button>
</div>
);
}
63 changes: 63 additions & 0 deletions docs-snippets/quickstart-react.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// snippet.quickstartReactImports
import { useEffect, useState } from 'react';
import PubNub from 'pubnub';
// snippet.end

// The React quickstart embeds the snippets below one by one.
// The complete file that combines them is docs-snippets/quickstart-react-app.tsx.
// This file is TSX, so docs-snippets/tsconfig.json (which only includes .ts files) does not compile it.

// snippet.quickstartReactInit
// Create the client once, outside the component, so re-renders reuse it
const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});
// snippet.end

export function Subscribe() {
// snippet.quickstartReactSubscribe
const [messages, setMessages] = useState<string[]>([]);

useEffect(() => {
const subscription = pubnub.channel('hello_world').subscription();

subscription.onMessage = (event) => {
setMessages((previous) => [...previous, `${event.publisher}: ${event.message}`]);
};
subscription.subscribe();

// Runs on unmount, and before React re-runs the effect in development (StrictMode)
return () => {
subscription.unsubscribe();
};
}, []);
// snippet.end

return <ul>{messages.map((message, index) => <li key={index}>{message}</li>)}</ul>;
}

export function Publish() {
// snippet.quickstartReactPublish
const [text, setText] = useState('');

const send = async () => {
if (!text.trim()) return;

try {
await pubnub.publish({ channel: 'hello_world', message: text });
setText('');
} catch (error) {
console.error(`Publish failed: ${error}`);
}
};
// snippet.end

return (
<>
<input value={text} onChange={(event) => setText(event.target.value)} />
<button onClick={send}>Send</button>
</>
);
}
56 changes: 56 additions & 0 deletions docs-snippets/quickstart-web.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>PubNub quickstart</title>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.13.0.3.js"></script>
</head>
<body>
<h1>PubNub quickstart</h1>
<ul></ul>
<input placeholder="Type a message" />
<button>Send</button>

<script>
const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});

pubnub.addListener({
message: (event) => {
// Add every incoming message to the list on the page
const item = document.createElement('li');
item.textContent = `${event.publisher}: ${event.message}`;
document.querySelector('ul')?.append(item);
},
status: (event) => {
if (event.category === 'PNConnectedCategory') {
console.log('Connected to PubNub');
}
},
});

const channel = pubnub.channel('hello_world');
const subscription = channel.subscription();
subscription.subscribe();

document.querySelector('button')?.addEventListener('click', async () => {
const input = document.querySelector('input');
if (!input || !input.value.trim()) return;

try {
const result = await pubnub.publish({
channel: 'hello_world',
message: input.value,
});
console.log(`Published, timetoken: ${result.timetoken}`);
input.value = '';
} catch (error) {
console.error(`Publish failed: ${error}`);
}
});
</script>
</body>
</html>
53 changes: 53 additions & 0 deletions docs-snippets/quickstart-web.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import PubNub from '../lib/types';

// The Web quickstart loads the SDK from the CDN, which exposes the PubNub global.
// The import above only lets the compiler check the snippets below.
// The runnable page that combines them is docs-snippets/quickstart-web.html.

// snippet.quickstartWebInit
const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'YOUR_USER_ID',
});
// snippet.end

// snippet.quickstartWebListeners
pubnub.addListener({
message: (event) => {
// Add every incoming message to the list on the page
const item = document.createElement('li');
item.textContent = `${event.publisher}: ${event.message}`;
document.querySelector('ul')?.append(item);
},
status: (event) => {
if (event.category === 'PNConnectedCategory') {
console.log('Connected to PubNub');
}
},
});
// snippet.end

// snippet.quickstartWebSubscribe
const channel = pubnub.channel('hello_world');
const subscription = channel.subscription();
subscription.subscribe();
// snippet.end

// snippet.quickstartWebPublish
document.querySelector('button')?.addEventListener('click', async () => {
const input = document.querySelector('input');
if (!input || !input.value.trim()) return;

try {
const result = await pubnub.publish({
channel: 'hello_world',
message: input.value,
});
console.log(`Published, timetoken: ${result.timetoken}`);
input.value = '';
} catch (error) {
console.error(`Publish failed: ${error}`);
}
});
// snippet.end
Loading