2. Sample App Utilizing the module - adonisv79/express-swish-protocol GitHub Wiki
Before proceeding, you are expected to know how to use ExpressJS and have a basic grasp of how it handles its middlewares. Make sure to create a new expressJS project and start with the following 'index.ts' template
import express, { Request, Response, NextFunction } from 'express';
import * as bodyParser from 'body-parser';
const port = 3000;
const app = express();
app.use(bodyParser.json());
app.post('/test/success', (req, res) => {
res.send({ status: 'success' });
});
app.post('/test/err', (req, res) => {
res.status(403).send({ status: 'error', message: 'THIS IS A TESTERROR' });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
install the express-swish-protocol
npm i express-swish-protocol --save
Nothing special about this yet so lets start adding our middleware. As mentioned, swish allows you to handle your session so we need to tell it what session id is generated when it needs one and what is the session object value when it needs to read/write into it. We can use databases or a memory store like Redis and memcache. but to simplify things, let's use a basic in-memory solution...
Add the following
import { swishSessionObject, Swish } from 'express-swish-protocol';
const sess: any = {};
async function onSessionCreate(): Promise<swishSessionObject> {
const d = new Date();
const sessionId = d.getTime().toString();
sess[sessionId] = { sessionId };
console.log(`Session '${sessionId}' created.`);
return sess[sessionId];
}
async function onSessionRetrieve(sessionId: string): Promise<swishSessionObject> {
return (sess[sessionId] || {});
}
async function onSessionUpdate(sessionId: string, delta: swishSessionObject): Promise<boolean> {
sess[sessionId]= { ...sess[sessionId], ...delta };
return true;
}
async function onSessionDestroy(sessionId: string): Promise<boolean> {
delete sess[sessionId];
return true;
}
const swish = new Swish(onSessionCreate, onSessionRetrieve, onSessionUpdate, onSessionDestroy);
// use our swish server middleware
app.use(swish.middleware);
- The 'sess' object will contain our 'unique' session keys and values
- onSessionCreate represents a function callback that gets triggered whenever the swish middleware received a handshake (new user connection). here we just generate a timestamp as a session id and return it.
- onSessionRetrieve represents a function callback that gets triggered whenever the swish middleware needs to validate and retrieve session data
- onSessionUpdate represents a function callback that gets triggered whenever the session properties must change
- onSessionDestroy represents a function callback that gets triggered whenever the swish middleware was given (by the client) a request to destroy the session. This ensures that the KILL request comes from the client and not anyone else.
- The swish class can be instantiated with the 4 callback mapped to it.
The final code can look somethin glike the following
import express, { Request, Response, NextFunction } from 'express';
import * as bodyParser from 'body-parser';
import { swishSessionObject, Swish } from 'express-swish-protocol';
// import express = require('express');
const sess: any = {};
async function onSessionCreate(): Promise<swishSessionObject> {
const d = new Date();
const sessionId = d.getTime().toString();
sess[sessionId] = {
swish: { sessionId },
};
console.log(`Session '${sessionId}' created.`);
return sess[sessionId].swish;
}
async function onSessionRetrieve(sessionId: string): Promise<swishSessionObject> {
console.log(`Session '${sessionId}' retrieved.`);
return (sess[sessionId] || {}).swish;
}
async function onSessionUpdate(sessionId: string, delta: swishSessionObject): Promise<boolean> {
sess[sessionId].swish = { ...sess[sessionId].swish, ...delta };
console.log(`Session '${sessionId}' updated...`);
return true;
}
async function onSessionDestroy(sessionId: string): Promise<boolean> {
delete sess[sessionId];
console.log(`Session '${sessionId}' has been terminated.`);
return true;
}
const swish = new Swish(onSessionCreate, onSessionRetrieve, onSessionUpdate, onSessionDestroy);
const port = 3000;
const app = express();
app.use(bodyParser.json());
// use our swish server middleware
app.use(swish.middleware);
app.post('/test/success', async (req: Request, res: Response, next: NextFunction) => {
console.log('Received request for /test/success');
await res.sendSwish(req, res, next, { status: 'success' });
});
app.post('/test/err', async (req: Request, res: Response, next: NextFunction) => {
console.log('Received request for /test/err');
await res.status(403).sendSwish(req, res, next, { status: 'error', message: 'THIS IS A TESTERROR' });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
This service is ready to run. To test this, use a swish compliant client like request-swish