directapi
v1.1.0
Published
Connect your server and client directly
Downloads
7
Readme
directapi
This is a simple Meteor-like module to make your server api easily accessible from the client.
Install
npm i --save directapi
Short overview
Direct API allows you to access your server interface directly from the client code like:
di({ url: 'http://localhost:9000/api' }).then((server) => {
/* Make your calls */
server.users.list().then(/* ... */);
});
Usage
Direct API uses connectors
concept. It means that you have to use special connector for a server and a client and they should be compatible.
Available connectors are:
express-server
:import es from 'directapi/connectors/express-server'
http-client
:import hc from 'directapi/connectors/http-client'
When you use directapi, you should provide JS object as an interface
. Everything in this object will be transformed to a promisified function, even constants. Nesting is supported. Also you can use this
safetly.
Server usage:
/* Your server API module */
let users = [];
const myserver = {
users: {
create: function (user) {
users.push(user);
return users.length - 1;
},
list: function () {
return users;
}
}
};
/* Your express application */
import di from 'directapi/core/server';
import es from 'directapi/connectors/express-server';
const app = express();
/* Build an express Router using express-server connector */
app.use('/api', di({}, myserver, es));
Client usage:
import di from 'directapi/core/client';
import hc from 'directapi/connectors/http-client';
di({
query: /* Your http query function like $.post/axios.post or a custom one */,
url: 'http://localhost:9000/api'
}, hc).then(function (myserver) {
/* Do things you want */
server.users.create({ name: 'mcfinley' }).then(function (id) {
/* Every method is promisified */
});
});