Last active
January 19, 2024 15:32
-
-
Save recursivecodes/8b7ad5fff4e9acf96692b67356dbd2c2 to your computer and use it in GitHub Desktop.
Install `@aws-sdk/client-ivs-realtime`, `@aws-sdk/client-ivschat` and run with `node simple-ivs-token-service.js`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as http from 'http'; | |
import * as url from 'url'; | |
import { CreateParticipantTokenCommand, IVSRealTimeClient } from "@aws-sdk/client-ivs-realtime"; | |
import { CreateChatTokenCommand, IvschatClient } from "@aws-sdk/client-ivschat"; | |
const ivsChatClient = new IvschatClient(); | |
const ivsRealtimeClient = new IVSRealTimeClient(); | |
const createChatToken = async (chatArn, userId, username) => { | |
const chatTokenInput = { | |
roomIdentifier: chatArn, | |
userId, | |
attributes: { username }, | |
capabilities: ['SEND_MESSAGE'], | |
sessionDurationInMinutes: 180, | |
}; | |
const createChatTokenRequest = new CreateChatTokenCommand(chatTokenInput); | |
return await ivsChatClient.send(createChatTokenRequest); | |
}; | |
const createStageToken = async (stageArn, attributes, capabilities, userId, duration) => { | |
const createStageTokenRequest = new CreateParticipantTokenCommand({ | |
attributes, | |
capabilities, | |
userId, | |
stageArn, | |
duration, | |
}); | |
const createStageTokenResponse = await ivsRealtimeClient.send(createStageTokenRequest); | |
return createStageTokenResponse; | |
}; | |
async function handler(req, res) { | |
const parsedUrl = url.parse(req.url, true); | |
if (parsedUrl.pathname === '/token') { | |
let body = ''; | |
req.on('data', chunk => { | |
body += chunk.toString(); | |
}); | |
req.on('end', async () => { | |
const params = JSON.parse(body); | |
res.writeHead(200, { 'Content-type': 'application/json' }); | |
const tokenResponse = await createStageToken( | |
params.stageArn, | |
params.attributes, | |
params.capabilities, | |
params.userId, | |
params.duration, | |
); | |
res.write(JSON.stringify(tokenResponse)); | |
res.end(); | |
}); | |
} | |
else if (parsedUrl.pathname === '/chat-token') { | |
let body = ''; | |
req.on('data', chunk => { | |
body += chunk.toString(); | |
}); | |
req.on('end', async () => { | |
const params = JSON.parse(body); | |
res.writeHead(200, { 'Content-type': 'application/json' }); | |
const tokenResponse = await createChatToken( | |
params.chatArn, | |
params.username, | |
params.userId, | |
); | |
res.write(JSON.stringify(tokenResponse)); | |
res.end(); | |
}); | |
} | |
else { | |
res.writeHead(404, { 'Content-type': 'text/plain' }); | |
res.write('404 Not Found'); | |
res.end(); | |
}; | |
} | |
const server = http.createServer(handler); | |
server.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment