Skip to content

Instantly share code, notes, and snippets.

@iKunalChhabra
Created November 24, 2024 06:20
Show Gist options
  • Save iKunalChhabra/a5832c896f43060cb091d0f81b0ba4e8 to your computer and use it in GitHub Desktop.
Save iKunalChhabra/a5832c896f43060cb091d0f81b0ba4e8 to your computer and use it in GitHub Desktop.
ES 6 Style import express app with websocket and data validation
import express from 'express';
import http from 'http';
import { WebSocketServer } from 'ws';
import fetch from 'node-fetch';
import Joi from 'joi';
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/ws', (req, res) => {
res.send('WebSocket connection address: ws://localhost:3000/ws');
});
app.get('/api/titanic', async (req, res) => {
try {
const schema = Joi.object({
page: Joi.number().integer().min(1).default(1),
pageSize: Joi.number().integer().min(1).default(10)
});
const { error, value } = schema.validate(req.query);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
const { page, pageSize } = value;
const response = await fetch('https://raw.githubusercontent.com/datasciencedojo/datasets/refs/heads/master/titanic.csv');
const csv = await response.text();
const rows = csv.split('\n');
const headers = rows[0].split(',');
const allData = rows.slice(1)
.filter(row => row.trim())
.map(row => {
const values = row.split(',');
const obj = {};
headers.forEach((header, index) => {
obj[header.trim()] = values[index] ? values[index].trim() : null;
});
return obj;
});
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const paginatedData = allData.slice(startIndex, endIndex);
res.json({
totalRows: allData.length,
page,
pageSize,
data: paginatedData,
remainingRows: Math.max(0, allData.length - endIndex)
});
} catch (error) {
console.error('Error fetching Titanic data:', error);
res.status(500).json({ error: 'Failed to fetch Titanic data' });
}
});
wss.on('connection', (ws) => {
console.log('A user connected');
ws.on('message', (msg) => {
const message = msg.toString();
console.log('Message received:', message);
ws.send('Server received: ' + message);
});
ws.on('close', () => {
console.log('User disconnected');
});
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`WebSocket connection address: ws://localhost:${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment