eproxe-express-binding v3.0.0
eproxe-express-binding
Install
npm i eproxe-express-bindingpnpm add eproxe-express-bindingUsage
Convetions
This exntesion relies method naming conventions to keep the syntax to a minimum
- methods starting with
getwill result inGETroutes, the parameters passed to the method call will be parsed from the query parameters on the request, the parameters will be human readable using JSON->URL - methods starting with
deletewill result inDELETEroutes, the parameters passed to the method call will be parsed from the query parameters on the request, the parameters will be human readable using JSON->URL - methods starting with
postwill result inPOSTroutes, the parameters passed to the method call will be parsed from the request's body - methods starting with
putwill result inPUTroutes, the parameters passed to the method call will be parsed from the request's body - defaults to
postif none of these convetions are met
Example
server.ts
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { toExpress } from 'eproxe-express-binding';
import api from './api';
const app = express();
const port = 3000;
app.use(
cors({
origin: 'http://localhost:5173',
})
);
app.use(bodyParser.json());
// create routes from the api object
const routes = toExpress(api);
app.use(routes);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});see a full example here
Accessing request/response
eproxe tries to abstract most of the request/response interface from the library consumer, but sometimes we must still use it when writing more complicated code
in these scenarios we can either:
Context (Recommended)
as a way of life, i cannot reccomend enough you use context inside express, it kinda makes you wonder why it isnt like this in the first place taking the power of context and hooks known and loved by react devs into node here is a short example of accessing the request/response in our api using express context
app.ts
import { ExpressProvider } from '@sgty/kontext-express';
import api from './api';
// wrap the app with the express context
app.use(ExpressProvider());
app.use(toExpress(api));api/index.ts
import { useExpress } from '@sgty/kontext-express';
const api = {
doSomething() {
const { req, res } = useExpress();
res.setHeader('is-using-context', 'absolutely');
return `something was done here: ${req.originalUrl}`;
},
};
export default api;see more about context in node and express here
Middleware
write an express middleware, we can invoke our code before, or after the original eproxe code is run