Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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>
- );
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement