npm i replicax --save
- π Usage
- π Auto Reload
- π‘ HTTP Methods
- π Middleware
- π Ready for Production (HTTPS)
- π Issues
- π€ Author
const { replicax } = require('replicax');
const app = replicax();
// Simple GET route
app.get('/', (req, res) => {
res.json({ message: 'Hello from Replicax!' });
});
// Route with parameters
app.get('/users/:id', (req, res) => {
res.json({ userId: req.params.id });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
// package.json
"scripts": {
"start": "replicax index.js"
},
/lib/watch.js
- File watcher that automatically restarts your server when index.js
files change of your main project, with debouncing to avoid rapid restarts, ignores node_modules
app.get('/users', (req, res) => {
res.json({ users: getAllUsers() });
});
app.post('/users', async (req, res) => {
const newUser = createUser(req.body);
res.status(201).json(newUser);
});
app.put('/users/:id', (req, res) => {
updateUser(req.params.id, req.body);
res.json({ success: true });
});
app.patch('/users/:id', (req, res) => {
partiallyUpdateUser(req.params.id, req.body);
res.json({ updated: true });
});
app.delete('/users/:id', (req, res) => {
deleteUser(req.params.id);
res.status(204).end();
});
app.route('/articles/:id')
.get((req, res) => res.json(getArticle(req.params.id)))
.put((req, res) => res.json(updateArticle(req.params.id, req.body)))
.delete((req, res) => res.status(204).end());
// Authentication middleware
app.use('/admin', (req, res, next) => {
if (req.headers.authorization === 'secret') {
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
});
// define middleware
const authMiddleware = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
};
// use any where or a particular route
app.get('/protected', authMiddleware, (req, res) => {
res.json({ data: 'Secret data' });
});
const fs = require('fs');
const { replicax } = require('replicax');
const app = replicax();
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
app.listen(443, () => {
console.log('HTTPS server running');
}, { https: true, httpsOptions: options });