Skip to content

Instantly share code, notes, and snippets.

@sahilrajput03
Last active August 4, 2022 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahilrajput03/989ecbf100eca5714ff9ccb01dd7c7e4 to your computer and use it in GitHub Desktop.
Save sahilrajput03/989ecbf100eca5714ff9ccb01dd7c7e4 to your computer and use it in GitHub Desktop.
rpc-demo snippet
// File: server-functions.js
module.exports.test = () => 'works!'
module.exports.yoy = (message) => {
return message + ' from server..'
}
module.exports.cat = (body) => {
const {say} = body
return 'Cat says:' + say + '!!'
}
module.exports.love = (name1, name2) => {
return `God loves: ${name1} and ${name2}`
}
// On error rpc send status: 400 (BAD REQUEST) and body as `err`
module.exports.rain = (name1, name2) => {
const messg = `${name1} does not like ${name2}`
let err = {name: 'RAIN AWAY', message: 'SUN DOWN'}
throw err
}
// On calling any someNonExistingFunction rpc send status: 404 (NOT FOUND)
// and sends message about using using non-existing function
// File: server.js
const express = require('express')
const createRpcPostRoute = require('rpc-middleware')
const fns = require('./server-functions')
const PORT = 8080
const app = express()
app.use(express.json())
// Serving static index.html on route /
app.get('/', (_, res) => res.sendFile(__dirname + '/index.html'))
// This calls: `app.post(route, functionMiddleware)` internally
createRpcPostRoute('/rpc', fns, app)
// FYI: You can create multiple rpc routes for different version of an api
// createRpcPostRoute('/rpc/v2', ver2fns, app)
app.listen(PORT, () => {
console.log('Server started on port:', PORT)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment