This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
SyncWebExpress.ts
64 lines (56 loc) · 1.58 KB
/
SyncWebExpress.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @module @raincatcher/datasync-cloud
*/
import { getLogger } from '@raincatcher/logger';
import * as Express from 'express';
import * as sync from 'fh-sync';
import * as path from 'path';
const logger = getLogger();
/**
* Expose Feedhenry Sync API using express middleware
*/
export class SyncExpressMiddleware {
private router: Express.Router;
private prefix: string;
/**
* @field prefix - used to create api endpoint
*/
constructor(prefix: string) {
this.router = Express.Router();
this.prefix = prefix;
}
/**
* Create express router for sync endpoints
*/
public createSyncExpressRouter() {
const apiURI = path.join(this.prefix + '/:datasetId');
logger.debug('Creating sync endpoint');
const syncRoute = this.router.route(apiURI);
/**
* Sync express api required for sync clients
* All sync clients will call that endpoint to sync data
*/
syncRoute.post(this.syncHandler);
return this.router;
}
/** Returns router instance */
public getRouter() {
return this.router;
}
/**
* Middleware handler responsible for calling sync api
*/
private syncHandler(req: Express.Request, res: Express.Response) {
const datasetId = req.params.datasetId;
const params = req.body;
sync.invoke(datasetId, params, function(err: any, result: any) {
if (err) {
// tslint:disable-next-line:no-console
logger.error('Error when processing sync request', { err });
return res.status(500).json(err);
}
return res.json(result);
});
}
}
export default SyncExpressMiddleware;