Skip to content

Instantly share code, notes, and snippets.

@RaymondBenc
Last active October 1, 2019 15:06
Show Gist options
  • Save RaymondBenc/4d37fcccb225e9d446636d465fa04f03 to your computer and use it in GitHub Desktop.
Save RaymondBenc/4d37fcccb225e9d446636d465fa04f03 to your computer and use it in GitHub Desktop.
Example using Unite Backend to Connect to SEPHP

Event Listener

You need an event listener in Unite for API Router and in your /srv/HelloWorld/APIRouter-match.js file you need the following:

const app = require('app');

async function call (method, endpoint, query = {}) {
    /**
     * The following two settings are borrowed from the SEPHP Bridge app
     */
    const url = await app.setting('sephp:url');
    const token = await app.setting('sephp:token');

    let search = '';
    let iteration = 0;
    let props = {};
    for (const key of Object.keys(query)) {
        iteration++;
        if (iteration !== 1) {
            search += '&';
        }
        search += key + '=' + encodeURIComponent(query[key]);
    }
    if (search && method === 'GET') {
        endpoint = endpoint + '?' + search;
    }
    if (method !== 'GET') {
        props.body = JSON.stringify(query);
    }
    const request = await app.fetch(url + endpoint, {
        method: method,
        ...props,
        headers: {
            'SE-Unite-Token': token,
            'Content-Type': 'application/json'
        }
    });
    return request.json();
}

module.exports = async function ({router}) {
    // This endpoint will translate to /api/@Acme/HelloWorld/groups
    router.get('/groups', async (req, res) => {
        res({
            records: await call('GET', '/bridge/api/groups')
        });
    });
};

To call this endpoint from a frontend component we will use our /hello-world controller as an example:

import React from 'react';
import app from '@SE/Core/App';
import Controller from '@SE/Core/Page/Controller';
import Card from '@SE/Core/Card';

export default class HelloWorldControllerHome extends React.Component {
    static propTypes = {};

    constructor (props) {
        super(props);

        this.state = {
            ready: false,
            records: []
        };
    }

    componentDidCatch (error, info) {
        app.withException(error, info);
    }

    componentDidMount () {
        app.api('/@Acme/HelloWorld/groups')
            .filter()
            .then(response => {
                this.setState({
                    ready: true,
                    records: response.records
                });
            });
    }

    renderGroups () {
        if (!this.state.ready) {
            return null;
        }
        return (
            <Card title="Groups">
                <div className="list-group">
                {this.state.records.map(record => (
                    <div key={record.group_id} className="list-group-item">
                        {record.title}
                    </div>
                ))}
                </div>
            </Card>
        );
    }

    render () {
        return (
            <Controller route="Acme:HelloWorld:home" title="Hello World!" ready={this.state.ready}>
                {this.renderGroups()}
            </Controller>
        );
    }
}
@RaymondBenc
Copy link
Author

SEPHP Endpoint

On the SEPHP side of things we are using our default bridge as the example and this endpoint exists here:
https://github.com/SocialEngine/sephp-unite-bridge/blob/master/src/application/modules/UniteBridge/ApiResource/Groups.php#L3

If you wish to use your own endpoint the token verification can be found here:
https://github.com/SocialEngine/sephp-unite-bridge/blob/master/src/application/modules/UniteBridge/Controller/Base.php#L6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment