@cuecue/http 0.0.23 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +638 -0
  2. package/package.json +9 -6
  3. package/lib/index.js +0 -1197
package/dist/index.js ADDED
@@ -0,0 +1,638 @@
1
+ import express, { Router } from 'express';
2
+ import { isArray } from 'lodash';
3
+ import { Parser, transforms } from 'json2csv';
4
+ import { BaseInput, BaseOutput } from '@cuecue/core';
5
+ import bodyParser from 'body-parser';
6
+ import { createServer } from 'http';
7
+ import cors from 'cors';
8
+ import createSession from 'express-session';
9
+ import createDebug from 'debug';
10
+ import axios from 'axios';
11
+ import StateMachine from 'javascript-state-machine';
12
+ import EventEmitter from 'wolfy87-eventemitter';
13
+
14
+ const createApi = (app, input, externalRouter = null) => {
15
+ const router = externalRouter === null ? new Router() : externalRouter;
16
+
17
+ const sendNotFound = res => {
18
+ res.status(404).json({
19
+ success: false,
20
+ error: 'not_found'
21
+ });
22
+ };
23
+
24
+ const getUserId = req => req.header('X-User-Id') || null;
25
+
26
+ const downloadCSV = (res, fileName, data) => {
27
+ const json2csv = new Parser({
28
+ transforms: [transforms.flatten('.')]
29
+ });
30
+ const csv = json2csv.parse(data);
31
+ res.header('Content-Type', 'text/csv');
32
+ res.attachment(fileName);
33
+ return res.send(csv);
34
+ };
35
+
36
+ router.get('/', async (req, res) => {
37
+ res.json({
38
+ message: 'Welcome to CueCue'
39
+ });
40
+ });
41
+ router.get('/cues', async (req, res) => {
42
+ const cues = await app.getCues();
43
+ res.json(cues);
44
+ });
45
+ router.get('/cues/current', async (req, res) => {
46
+ const cue = await app.getSessionCue();
47
+ res.json(cue);
48
+ });
49
+ router.post('/cues/define', async (req, res) => {
50
+ const {
51
+ body = null
52
+ } = req || {};
53
+
54
+ if (body === null) {
55
+ sendNotFound(res);
56
+ return;
57
+ }
58
+
59
+ try {
60
+ await app.define(body);
61
+ res.json({
62
+ success: true
63
+ });
64
+ } catch (e) {
65
+ res.json({
66
+ success: false
67
+ });
68
+ }
69
+ });
70
+ router.get('/cues/:id', async (req, res) => {
71
+ const cues = await app.getCues();
72
+ const cue = cues.find(it => it.id === req.params.id) || null;
73
+
74
+ if (cue === null) {
75
+ sendNotFound(res);
76
+ return;
77
+ }
78
+
79
+ res.json(cue);
80
+ });
81
+ router.post('/cues/:id', async (req, res) => {
82
+ const cues = await app.getCues();
83
+ const cue = cues.find(it => it.id === req.params.id) || null;
84
+
85
+ if (cue === null) {
86
+ sendNotFound(res);
87
+ return;
88
+ }
89
+
90
+ try {
91
+ await input.cue(cue.id, req.body || null);
92
+ res.json({
93
+ success: true
94
+ });
95
+ } catch (e) {
96
+ res.json({
97
+ success: false
98
+ });
99
+ }
100
+ });
101
+ router.get('/cues/:id/interactions', async (req, res) => {
102
+ const cues = await app.getCues();
103
+ const cue = cues.find(it => it.id === req.params.id) || null;
104
+
105
+ if (cue === null) {
106
+ sendNotFound(res);
107
+ return;
108
+ }
109
+
110
+ const interactions = await app.getInteractionsByCue(cue.id);
111
+ res.json(interactions);
112
+ });
113
+ router.post('/uncue', async (req, res) => {
114
+ try {
115
+ await app.uncue();
116
+ res.json({
117
+ success: true
118
+ });
119
+ } catch (e) {
120
+ res.json({
121
+ success: false
122
+ });
123
+ }
124
+ });
125
+ router.get('/interactions', async (req, res) => {
126
+ const userId = getUserId(req);
127
+ const interactions = userId !== null ? await app.getInteractionsByUser(userId) : await app.getInteractions();
128
+ res.json(interactions);
129
+ });
130
+ router.post('/interactions', async (req, res) => {
131
+ try {
132
+ const userId = getUserId(req);
133
+ await input.interact(req.body, userId);
134
+ res.json({
135
+ success: true
136
+ });
137
+ } catch (e) {
138
+ res.json({
139
+ success: false
140
+ });
141
+ }
142
+ });
143
+ router.get('/session/current', async (req, res) => {
144
+ const {
145
+ session
146
+ } = app;
147
+
148
+ if (session === null) {
149
+ sendNotFound(res);
150
+ return;
151
+ }
152
+
153
+ res.json(session.id);
154
+ });
155
+ router.get('/session/:id', async (req, res) => {
156
+ const {
157
+ session
158
+ } = app; // TODO: Find a session?
159
+
160
+ if (session === null) {
161
+ sendNotFound(res);
162
+ return;
163
+ }
164
+
165
+ res.json(session);
166
+ });
167
+ router.get('/app/state', async (req, res) => {
168
+ const {
169
+ state
170
+ } = app.state;
171
+
172
+ if (state === null) {
173
+ sendNotFound(res);
174
+ return;
175
+ }
176
+
177
+ res.json(state);
178
+ });
179
+ router.get('/export/sessions.:format', async (req, res) => {
180
+ const format = req.params.format || null;
181
+ const items = await app.store.getItems('sessions', {}, true);
182
+
183
+ if (items === null || !isArray(items)) {
184
+ sendNotFound(res);
185
+ return;
186
+ }
187
+
188
+ if (format === 'csv') {
189
+ downloadCSV(res, 'sessions.csv', items);
190
+ return;
191
+ }
192
+
193
+ res.json(items);
194
+ });
195
+ router.get('/export/interactions.:format', async (req, res) => {
196
+ const format = req.params.format || null;
197
+ const items = await app.store.getItems('interactions', {}, true);
198
+
199
+ if (items === null || !isArray(items)) {
200
+ sendNotFound(res);
201
+ return;
202
+ }
203
+
204
+ if (format === 'csv') {
205
+ downloadCSV(res, 'interactions.csv', items);
206
+ return;
207
+ }
208
+
209
+ res.json(items);
210
+ });
211
+ router.get('/export/cues.:format', async (req, res) => {
212
+ const format = req.params.format || null;
213
+ const items = await app.store.getItems('cues', {}, true);
214
+
215
+ if (items === null || !isArray(items)) {
216
+ sendNotFound(res);
217
+ return;
218
+ }
219
+
220
+ if (format === 'csv') {
221
+ downloadCSV(res, 'cues.csv', items);
222
+ return;
223
+ }
224
+
225
+ res.json(items);
226
+ });
227
+ return router;
228
+ };
229
+
230
+ class HttpInput extends BaseInput {
231
+ constructor(opts = {}) {
232
+ super(opts);
233
+ this.options = {
234
+ port: process.env.PORT || 8080,
235
+ publicPath: null,
236
+ path: process.env.ROUTER_PATH || '/api',
237
+ ...opts
238
+ };
239
+ this.express = null;
240
+ this.session = null;
241
+ this.http = null;
242
+ this.path = '/';
243
+ this.router = new Router();
244
+ this.debug = createDebug('cuecue:input:http');
245
+ }
246
+
247
+ cue(cue, extraData = null) {
248
+ this.emit('command', 'cue', cue, extraData);
249
+ }
250
+
251
+ interact(data, interactionId = null) {
252
+ this.emit('command', 'interact', data, interactionId);
253
+ }
254
+
255
+ getRouter() {
256
+ return this.router;
257
+ }
258
+
259
+ setRouter(router) {
260
+ this.router = router;
261
+ }
262
+
263
+ use(...args) {
264
+ return this.express.use(...args);
265
+ }
266
+
267
+ async onInit() {
268
+ this.emit('init');
269
+ const {
270
+ path
271
+ } = this.options;
272
+ this.express = express();
273
+ this.http = createServer(this.express);
274
+ this.session = createSession({
275
+ secret: 'my-secret-session',
276
+ resave: true,
277
+ saveUninitialized: true
278
+ });
279
+ this.express.use(cors());
280
+ this.express.use(bodyParser.json());
281
+ this.express.use(bodyParser.urlencoded({
282
+ extended: false
283
+ })); // Use express-session middleware for express
284
+
285
+ this.express.use(this.session);
286
+
287
+ if (this.router !== null) {
288
+ this.use(path, this.router);
289
+ }
290
+
291
+ await this.startServer();
292
+ }
293
+
294
+ async onDestroy() {
295
+ this.debug('destroying...');
296
+ this.emit('destroy');
297
+
298
+ try {
299
+ await this.stopServer();
300
+ } catch (e) {
301
+ this.debug('destroy error %O', e);
302
+ }
303
+
304
+ this.express = null;
305
+ this.http = null;
306
+ this.session = null;
307
+ }
308
+
309
+ onStarted() {
310
+ const {
311
+ port
312
+ } = this.options;
313
+ this.debug(`started on *:${port}`);
314
+ return process.nextTick(() => this.emit('started'));
315
+ }
316
+
317
+ startServer() {
318
+ const {
319
+ port
320
+ } = this.options;
321
+ return new Promise((resolve, reject) => {
322
+ this.http.listen(port, err => {
323
+ if (err) {
324
+ reject(err);
325
+ return;
326
+ }
327
+
328
+ resolve();
329
+ });
330
+ });
331
+ }
332
+
333
+ stopServer() {
334
+ this.debug('Stopping...');
335
+ return new Promise((resolve, reject) => {
336
+ this.http.close(err => {
337
+ if (err) {
338
+ reject(err);
339
+ return;
340
+ }
341
+
342
+ resolve();
343
+ });
344
+ });
345
+ }
346
+
347
+ }
348
+
349
+ class ApiInput extends HttpInput {
350
+ constructor(opts = {}) {
351
+ const {
352
+ app,
353
+ ...options
354
+ } = opts;
355
+ super(options);
356
+ this.router = createApi(app, this);
357
+ }
358
+
359
+ }
360
+
361
+ class HttpOutput extends BaseOutput {
362
+ constructor(opts = {}) {
363
+ super({
364
+ method: 'POST',
365
+ ...opts
366
+ });
367
+ this.debug = createDebug('cuecue:output:http');
368
+ }
369
+
370
+ cue(cue, extraData = null) {
371
+ this.command('cue', cue, extraData);
372
+ }
373
+
374
+ cues(cues) {
375
+ this.command('cues', cues);
376
+ }
377
+
378
+ interact(data, interactionId = null) {
379
+ this.command('interact', data, interactionId);
380
+ }
381
+
382
+ interaction(interaction) {
383
+ this.command('interaction', interaction);
384
+ }
385
+
386
+ uninteraction(interactionId) {
387
+ this.command('uninteract', interactionId);
388
+ }
389
+
390
+ uninteractions(interactionIds) {
391
+ this.command('uninteractions', interactionIds);
392
+ }
393
+
394
+ async command(command, ...args) {
395
+ const {
396
+ transformCommand = null,
397
+ transformMessage = null,
398
+ acceptCommand = null
399
+ } = this.options;
400
+ const value = transformCommand !== null ? await transformCommand(command, args) : {
401
+ command,
402
+ args
403
+ };
404
+
405
+ if (value === false) {
406
+ this.debug('command canceled: %s %o', command, args);
407
+ return Promise.resolve();
408
+ }
409
+
410
+ const {
411
+ command: finalCommand = command,
412
+ args: finalArgs = args
413
+ } = value || {};
414
+
415
+ if (acceptCommand !== null && !acceptCommand(finalCommand, finalArgs)) {
416
+ this.debug('command refused: %s %o', finalCommand, finalArgs);
417
+ return Promise.resolve();
418
+ }
419
+
420
+ this.debug('command: %s message: %o', finalCommand, finalArgs);
421
+ const message = {
422
+ command: finalCommand,
423
+ args: finalArgs
424
+ };
425
+ const payload = transformMessage !== null ? await transformMessage(message) : message;
426
+ return this.request(payload);
427
+ }
428
+
429
+ async request(payload) {
430
+ const {
431
+ url,
432
+ method,
433
+ headers
434
+ } = this.options;
435
+ return axios({
436
+ url,
437
+ method,
438
+ headers,
439
+ data: payload
440
+ });
441
+ }
442
+
443
+ }
444
+
445
+ class Server extends EventEmitter {
446
+ constructor(opts = {}) {
447
+ super();
448
+ this.options = {
449
+ port: process.env.PORT || 8080,
450
+ publicPath: null,
451
+ ...opts
452
+ };
453
+ this.onInit = this.onInit.bind(this);
454
+ this.onInitialized = this.onInitialized.bind(this);
455
+ this.onDestroy = this.onDestroy.bind(this);
456
+ this.onDestroyed = this.onDestroyed.bind(this);
457
+ this.onStart = this.onStart.bind(this);
458
+ this.onStop = this.onStop.bind(this);
459
+ this.onStarted = this.onStarted.bind(this);
460
+ this.onStopped = this.onStopped.bind(this);
461
+ this.app = null;
462
+ this.session = null;
463
+ this.http = null;
464
+ this.debug = createDebug('cuecue:server');
465
+ this.state = new StateMachine({
466
+ transitions: [{
467
+ name: 'init',
468
+ from: 'none',
469
+ to: 'initialized'
470
+ }, {
471
+ name: 'destroy',
472
+ from: '*',
473
+ to: 'none'
474
+ }, {
475
+ name: 'start',
476
+ from: ['initialized', 'stopped'],
477
+ to: 'started'
478
+ }, {
479
+ name: 'stop',
480
+ from: 'started',
481
+ to: 'stopped'
482
+ }],
483
+ methods: {
484
+ onBeforeInit: this.onInit,
485
+ onAfterInit: this.onInitialized,
486
+ onBeforeDestroy: this.onDestroy,
487
+ onAfterDestroy: this.onDestroyed,
488
+ onBeforeStart: this.onStart,
489
+ onAfterStart: this.onStarted,
490
+ onBeforeStop: this.onStop,
491
+ onAfterStop: this.onStopped
492
+ }
493
+ });
494
+ this.init();
495
+ }
496
+
497
+ init() {
498
+ return this.state.init();
499
+ }
500
+
501
+ destroy() {
502
+ return this.state.destroy();
503
+ }
504
+
505
+ async start() {
506
+ if (!this.initialized()) {
507
+ await this.init();
508
+ }
509
+
510
+ return this.state.start();
511
+ }
512
+
513
+ stop() {
514
+ return this.state.stop();
515
+ }
516
+
517
+ initialized() {
518
+ return this.state.is('initialized');
519
+ }
520
+
521
+ started() {
522
+ return this.state.is('started');
523
+ }
524
+
525
+ stopped() {
526
+ return this.state.is('stopped');
527
+ }
528
+
529
+ destroyed() {
530
+ return this.state.is('destroyed');
531
+ }
532
+
533
+ use(...args) {
534
+ return this.app.use(...args);
535
+ }
536
+
537
+ async onInit() {
538
+ this.emit('init');
539
+ this.app = express();
540
+ this.http = createServer(this.app);
541
+ this.session = createSession({
542
+ secret: 'my-secret-session',
543
+ resave: true,
544
+ saveUninitialized: true
545
+ });
546
+ this.app.use(cors());
547
+ this.app.use(bodyParser.json());
548
+ this.app.use(bodyParser.urlencoded({
549
+ extended: false
550
+ })); // Use express-session middleware for express
551
+
552
+ this.app.use(this.session);
553
+ await this.startServer();
554
+ }
555
+
556
+ onInitialized() {
557
+ this.debug('initialized');
558
+ return process.nextTick(() => this.emit('initialized'));
559
+ }
560
+
561
+ async onDestroy() {
562
+ this.debug('destroying...');
563
+ this.emit('destroy');
564
+
565
+ try {
566
+ await this.stopServer();
567
+
568
+ if (this.session !== null && typeof this.session.close !== 'undefined') {
569
+ this.session.close();
570
+ }
571
+ } catch (e) {
572
+ this.debug('onDestroy error %O', e);
573
+ }
574
+
575
+ this.app = null;
576
+ this.http = null;
577
+ }
578
+
579
+ onDestroyed() {
580
+ this.debug('destroyed');
581
+ return process.nextTick(() => this.emit('destroyed'));
582
+ }
583
+
584
+ onStart() {
585
+ this.debug('starting...');
586
+ this.emit('start');
587
+ }
588
+
589
+ onStarted() {
590
+ const {
591
+ port
592
+ } = this.options;
593
+ this.debug(`started on *:${port}`);
594
+ return process.nextTick(() => this.emit('started'));
595
+ }
596
+
597
+ onStop() {
598
+ this.emit('stop');
599
+ }
600
+
601
+ onStopped() {
602
+ this.debug('Stopped.');
603
+ return process.nextTick(() => this.emit('stopped'));
604
+ }
605
+
606
+ startServer() {
607
+ const {
608
+ port
609
+ } = this.options;
610
+ return new Promise((resolve, reject) => {
611
+ this.http.listen(port, err => {
612
+ if (err) {
613
+ reject(err);
614
+ return;
615
+ }
616
+
617
+ resolve();
618
+ });
619
+ });
620
+ }
621
+
622
+ stopServer() {
623
+ this.debug('Stopping...');
624
+ return new Promise((resolve, reject) => {
625
+ this.http.close(err => {
626
+ if (err) {
627
+ reject(err);
628
+ return;
629
+ }
630
+
631
+ resolve();
632
+ });
633
+ });
634
+ }
635
+
636
+ }
637
+
638
+ export { ApiInput, HttpInput as Input, HttpOutput as Output, Server, createApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuecue/http",
3
- "version": "0.0.23",
3
+ "version": "0.0.27",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "javascript"
@@ -29,16 +29,19 @@
29
29
  }
30
30
  ],
31
31
  "license": "ISC",
32
- "main": "lib/index.js",
32
+ "main": "dist/index.js",
33
33
  "files": [
34
- "lib"
34
+ "dist"
35
35
  ],
36
36
  "scripts": {
37
- "prepare": "../../scripts/prepare-package.sh"
37
+ "clean": "rm -rf dist",
38
+ "build": "rollup --config ../../rollup.config.js",
39
+ "prepare": "npm run clean && npm run build"
38
40
  },
39
41
  "dependencies": {
40
42
  "@babel/runtime": "^7.12.5",
41
- "@cuecue/core": "^0.0.23",
43
+ "@cuecue/core": "^0.0.27",
44
+ "axios": "^0.24.0",
42
45
  "body-parser": "^1.19.0",
43
46
  "commander": "^7.0.0",
44
47
  "cors": "^2.8.5",
@@ -53,5 +56,5 @@
53
56
  "publishConfig": {
54
57
  "access": "public"
55
58
  },
56
- "gitHead": "0741fd1f625f6cf9b9b4be588cf5349c713213c1"
59
+ "gitHead": "2c305c0d1c0b13469fe74e2b928c0b45744c8ac0"
57
60
  }