api.io
Small node.js framework for easily exposing an APIa over websockets to clients.
Tests
Usage
Expose an API in node.js
"use strict";
const http = require("http");
const api = require("api.io");
const myApi = api.register("myApi", {
VALUE: "const",
notApi: () => {
},
sum: api.export((session, a, b) => {
return a + b;
}),
sumAsync: api.export(async (session, a, b) => {
return a + b;
}),
send: api.export((session, data) => {
myApi.emit("event4", data);
})
});
const myApi2 = api.register("myApi2", {
send: api.export(async (session) => {
myApi2.emit("eventX", "Over myApi2");
})
});
let connectionSubscription;
let disconnectionSubscription;
let server;
const run = async (port) => {
server = new http.Server();
await api.start(server);
server.listen(port);
connectionSubscription = api.on("connection", async (client) => {
client.session.username = "guest";
});
disconnectionSubscription = api.on("disconnection", (client) => {
});
myApi.emit("event1", "Hello World!");
myApi.emit("event2", "Hello World!", { username: "guest" });
for (const value of [ 1, 2, 3, 4, 5 ]) {
myApi.emit("event3", value);
}
};
const stop = async () => {
api.off(connectionSubscription);
api.off(disconnectionSubscription);
await api.stop();
server.close();
};
run();
Use an API from a node.js or webpack:ed client
"use strict";
const api = require("api.io-client");
const run = async () => {
await api.connect({
hostname: "localhost",
port: 8080
}, (status, message) => {
if (status === "timeout") {
console.error(message);
process.exit(255);
} else if (status === "disconnect") {
console.error("Disconnected from server, will attempt to reconnect...");
} else if (status === "reconnect") {
console.log("Reconnected to server");
}
});
console.log(api.myApi.CONST_VALUE);
const result = await api.myApi.sum(1, 2);
const result2 = await api.myApi.sumAsync(1, 3);
const subscription1 = api.myApi.on("event1", async (data) => {
});
const subscription2 = api.myApi.on("event2", (data) => {
});
const subscription3 = api.myApi.on("event3", (data) => {
}, {
id: 1,
query: { $gte: 4 }
});
api.myApi.off(subscription1);
api.myApi.off(subscription2);
api.myApi.off(subscription3);
};
run();