· 6 years ago · Oct 19, 2019, 11:18 PM
1# Event Listener
2You need an event listener in Unite for `API Router` and in your `/srv/HelloWorld/APIRouter-match.js` file you need the following:
3```
4const app = require('app');
5
6async function call (method, endpoint, query = {}) {
7 /**
8 * The following two settings are borrowed from the SEPHP Bridge app
9 */
10 const url = await app.setting('sephp:url');
11 const token = await app.setting('sephp:token');
12
13 let search = '';
14 let iteration = 0;
15 let props = {};
16 for (const key of Object.keys(query)) {
17 iteration++;
18 if (iteration !== 1) {
19 search += '&';
20 }
21 search += key + '=' + encodeURIComponent(query[key]);
22 }
23 if (search && method === 'GET') {
24 endpoint = endpoint + '?' + search;
25 }
26 if (method !== 'GET') {
27 props.body = JSON.stringify(query);
28 }
29 const request = await app.fetch(url + endpoint, {
30 method: method,
31 ...props,
32 headers: {
33 'SE-Unite-Token': token,
34 'Content-Type': 'application/json'
35 }
36 });
37 return request.json();
38}
39
40module.exports = async function ({router}) {
41 // This endpoint will translate to /api/@Acme/HelloWorld/groups
42 router.get('/groups', async (req, res) => {
43 res({
44 records: await call('GET', '/bridge/api/groups')
45 });
46 });
47};
48```
49To call this endpoint from a frontend component we will use our `/hello-world` controller as an example:
50```
51import React from 'react';
52import app from '@SE/Core/App';
53import Controller from '@SE/Core/Page/Controller';
54import Card from '@SE/Core/Card';
55
56export default class HelloWorldControllerHome extends React.Component {
57 static propTypes = {};
58
59 constructor (props) {
60 super(props);
61
62 this.state = {
63 ready: false,
64 records: []
65 };
66 }
67
68 componentDidCatch (error, info) {
69 app.withException(error, info);
70 }
71
72 componentDidMount () {
73 app.api('/@Acme/HelloWorld/groups')
74 .filter()
75 .then(response => {
76 this.setState({
77 ready: true,
78 records: response.records
79 });
80 });
81 }
82
83 renderGroups () {
84 if (!this.state.ready) {
85 return null;
86 }
87 return (
88 <Card title="Groups">
89 <div className="list-group">
90 {this.state.records.map(record => (
91 <div key={record.group_id} className="list-group-item">
92 {record.title}
93 </div>
94 ))}
95 </div>
96 </Card>
97 );
98 }
99
100 render () {
101 return (
102 <Controller route="Acme:HelloWorld:home" title="Hello World!" ready={this.state.ready}>
103 {this.renderGroups()}
104 </Controller>
105 );
106 }
107}
108```