Illyoung Choi | 59820ed | 2019-06-24 17:01:00 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019-present Open Networking Foundation |
| 3 | |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | |
| 18 | (function () { |
| 19 | 'use strict'; |
| 20 | |
| 21 | const express = require('express'); |
| 22 | const {checkSchema, validationResult} = require('express-validator'); |
| 23 | const logger = require('../config/logger.js'); |
| 24 | const eventrouter = require('./eventrouter.js'); |
| 25 | |
| 26 | // HTTP REST interface for message intake |
| 27 | // POST method |
| 28 | // Message format: |
| 29 | // { |
| 30 | // topic: 'topic here', |
| 31 | // message: 'message body here' |
| 32 | // } |
| 33 | // e.g., /intake?topic=aaa&message=bbb |
| 34 | const intakeMessageInputValidator = { |
| 35 | topic: { |
| 36 | in: ['params', 'query'], |
| 37 | errorMessage: 'Message topic is null or empty', |
| 38 | }, |
| 39 | message: { |
| 40 | in: ['params', 'query'], |
| 41 | errorMessage: 'Message body is null or empty', |
| 42 | } |
| 43 | }; |
| 44 | |
| 45 | const intakeMessage = (req, res) => { |
| 46 | let errors = validationResult(req); |
| 47 | if(!errors.isEmpty()) { |
| 48 | res.status(400).send( |
| 49 | JSON.stringify({ |
| 50 | errors: errors.array() |
| 51 | }) |
| 52 | ); |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | let jsonMessage = req.body |
| 57 | logger.debug(`Received a message ${jsonMessage}`); |
| 58 | |
| 59 | // send the message to the event distributor |
Illyoung Choi | f0204da | 2019-07-25 09:38:36 -0700 | [diff] [blame] | 60 | eventrouter.emitEvent(jsonMessage.topic, jsonMessage.message); |
Illyoung Choi | 59820ed | 2019-06-24 17:01:00 -0700 | [diff] [blame] | 61 | |
| 62 | res.status(200).send({ |
| 63 | result: true |
| 64 | }); |
| 65 | return; |
| 66 | }; |
| 67 | |
| 68 | const getRouter = () => { |
| 69 | var routerInstance = new express.Router(); |
| 70 | routerInstance.use((req, res, next) => { |
| 71 | logger.info(`[REQ] ${req.method}, ${req.url}`); |
| 72 | next(); |
| 73 | }); |
| 74 | |
| 75 | // intake apis |
| 76 | routerInstance.post('/intake', checkSchema(intakeMessageInputValidator), intakeMessage); |
| 77 | return routerInstance; |
| 78 | }; |
| 79 | |
| 80 | module.exports = { |
| 81 | getRouter: getRouter |
| 82 | }; |
| 83 | })(); |