https://github.com/dobschal/javascript-proxy-fun
An example on how to use the JavaScript Proxy class.
https://github.com/dobschal/javascript-proxy-fun
Last synced: 8 months ago
JSON representation
An example on how to use the JavaScript Proxy class.
- Host: GitHub
- URL: https://github.com/dobschal/javascript-proxy-fun
- Owner: dobschal
- Created: 2023-02-01T08:20:18.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-02-01T10:44:00.000Z (over 3 years ago)
- Last Synced: 2025-06-02T14:56:03.510Z (about 1 year ago)
- Language: JavaScript
- Size: 962 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# Fun with JavaScript Proxy
Example implementation on how to use the JavaScript Proxy class.
Take a look into the `client/serverProxy.js` file:
```javascript
import { postData } from "./http.js";
export const server = new Proxy({}, {
get(_, key) {
return async (data) => {
return await postData(`/${key}`, data);
};
}
});
```
Instead of making a HTTP request to the server directly, we put a Proxy instance in between. This instance maps all method call to HTTP requests.
On the server side we map all request controllers, so that we can easily call them from the client side:
```javascript
const api = require("./api.js");
const app = express();
Object.keys(api).forEach(methodName => {
app.post(`/${methodName}`, api[methodName]);
});
```
The result looks like:
```javascript
// client.js loaded inot index.html
let username = "Aurelia";
await server.saveUsername(username);
// server.js (e.g. NodeJS)
const api = {
saveUsername(req, res) {
// ...update username from req.body in database
res.send({
message: `Updated username '${req.body}'.`
});
}
};
```