Session Creation and Joining the Session
The first thing we do is look up if we already have a session for the room we are generating. We keep an in-memory dictionary in roomToSessionIdDictionary, and if the room already has a session we just pull the session from the dictionary. We then use the Vonage Video Node SDK to create a client token by calling vonage.video.generateClientToken(), passing it the session ID and an object with some configuration. At the moment all we do is set the user to a moderator role for this simple demo. We then return the configured Application ID, Session ID, and Token back to the front end.
If the session does not exist, we create a new one with vonage.video.createSession(). This contacts the Vonage API and creates a session that users can connect to. We don't have any specific settings for this session, but here would be where we set up things like archiving rules and how the session should be handled, like routing or peer-to-peer. Then like before we create a token, and send all that information back to the browser.
// routes/index.js
async function createSession(response, roomName, sessionProperties = {}, role = 'moderator') {
let sessionId;
let token;
console.log(`Creating ${role} creds for ${roomName}`);
if (roomToSessionIdDictionary[roomName]) {
sessionId = roomToSessionIdDictionary[roomName];
// generate token for user
token = vonage.video.generateClientToken(sessionId, { role })
response.setHeader('Content-Type', 'application/json');
response.send({
applicationId: appId,
sessionId: sessionId,
token: token
});
} else {
try {
// Create the session
const session = await vonage.video.createSession(sessionProperties);
roomToSessionIdDictionary[roomName] = session.sessionId;
// generate token for user
token = vonage.video.generateClientToken(session.sessionId, { role });
response.setHeader('Content-Type', 'application/json');
response.send({
applicationId: appId,
sessionId: session.sessionId,
token: token
});
} catch(error) {
console.error("Error creating session: ", error);
response.status(500).send({ error: 'createSession error:' + error });
}
}
}