UNPKG

@sodacore/ws

Version:

Sodacore ws is a core plugin that extends the Http plugin offering WebSocket support to the Sodacore framework.

62 lines (61 loc) 2.9 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Middleware } from '@sodacore/http'; import { Inject } from '@sodacore/di'; import { v4 } from 'uuid'; import { Logger } from '@sodacore/core'; let UpgradeMiddleware = class UpgradeMiddleware { async handle(context) { // Only execute if connection is attempting to upgrade. const hConnection = context.getHeader('connection'); const hUpgrade = context.getHeader('upgrade'); if (hConnection !== 'Upgrade' || hUpgrade !== 'websocket') return; // Check if the request matches one of the paths. const requestPath = context.getUrl().pathname; const paths = Array.isArray(this.config.path) ? this.config.path : [this.config.path]; if (!paths.includes(requestPath)) return new Response('Not Implemented', { status: 501 }); // Let's get the request and server. const request = context.getRequest(); const server = context.getServer(); const id = v4(); const maxAge = 60 * 60 * 24; // 24 hours. // Log the upgrade. this.logger.info(`[MIDDLEWARE]: Upgrading http connection to WebSocket for path: "${requestPath}"`); // Attempt to upgrade. const status = server.upgrade(request, { data: { httpContext: context, }, headers: { // eslint-disable-next-line @typescript-eslint/naming-convention 'Set-Cookie': `sodacoreId=${id}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge};`, }, }); // If the status was successful, prevent the http service from responding. if (status) return true; // If we failed, return a 500. return new Response('Internal Server Error', { status: 500 }); } }; __decorate([ Inject('@ws:config'), __metadata("design:type", Object) ], UpgradeMiddleware.prototype, "config", void 0); __decorate([ Inject(), __metadata("design:type", Logger) ], UpgradeMiddleware.prototype, "logger", void 0); UpgradeMiddleware = __decorate([ Middleware() ], UpgradeMiddleware); export default UpgradeMiddleware;