Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active August 31, 2018 06:54
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 loilo/e3b40b31d9ec4fed3a97d78dda945098 to your computer and use it in GitHub Desktop.
Save loilo/e3b40b31d9ec4fed3a97d78dda945098 to your computer and use it in GitHub Desktop.
DNode Comfort Interface (Node.js Server, PHP Client)

Comfortable DNode

Thin API wrappers around Node's dnode and PHP's erasys/dnode-php-sync-client for improved developer ergonomy.

p_dnode.js

Example from the original dnode:

var server = dnode({
  transform : function (s, cb) {
    cb(s.replace(/[aeiou]{2,}/, 'oo').toUpperCase())
  }
});

The same example with p_dnode:

const server = p_dnode({
  transform (s) {
    return s.replace(/[aeiou]{2,}/, 'oo').toUpperCase()
  }
})

Tip: For asynchronous operations, return a Promise / use async functions.

DNode.php

Example from erasys/dnode-php-sync-client:

$dnode = new \DnodeSyncClient\Dnode();
$connection = $dnode->connect('localhost', 8080);
$response = $connection->call('echo', array('Hello, world!'));
var_dump($response);

The same example used with the DNode wrapper:

$connection = Dnode::connect('localhost', 8080);
$response = $connection->echo('Hello, world!');
var_dump($response);
<?php
require_once __DIR__ . "/vendor/erasys/dnode-php-sync-client/DnodeSyncClient.php";
class DNode
{
protected $connection;
public static function connect($host, $port)
{
return new self($host, $port);
}
protected function __construct($host, $port)
{
$dnode = new \DnodeSyncClient\Dnode();
$this->connection = $dnode->connect($host, $port);
}
public function __call($method, $args)
{
return $this->connection->call($method, $args);
}
}
/*
* p_dnode() is to be used just like dnode(), except that method definitions don't use callbacks but (may) return Promises.
* Works in Node 6+
*/
const dnode = require('dnode')
function p_dnode (methods) {
const config = Object
.keys(methods)
.reduce((carry, name) => {
const fn = methods[name]
return Object.assign(
{},
carry,
{
[name] (...args) {
const cb = args.pop()
Promise.resolve(fn(...args)).then(result => cb(result))
}
}
)
}, {})
return dnode(config)
}
Object.assign(p_dnode, dnode)
module.exports = p_dnode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment