AWS – 编写 API 函数
     发布在:JavaScript      浏览:6      评论:0 条评论

API Handler

const serverless = require('serverless-http');
const apiCompare = require('./apis/api_compare');

module.exports.compare = serverless(apiCompare);

API Compare Function

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const compareRepository = require('../repositories/repository_compare');
const utils = require('../utils/utils');

/** Cors */
const app = express();
app.use(cors({origin: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/** APIs */
app.get('/compare/retrieve-all', (req, res) => {
  compareRepository
      .getAllCompare()
      .then((result) => {
        const response = {data: result, message: 'Success'};
        return res.status(200).send(response);
      })
      .catch((error) => {
        const message = utils.errorFormatter(error).message;
        const response = {data: null, message: message};
        return res.status(400).send(response);
      });
});

// wrap express app instance with serverless http function
module.exports = app;

Compare Repository

'use strict';

const db = require('./db');
const dbName = process.env.DATABASE_NAME;
const tableName = dbName + '.compare';

const CompareRepository = {
  getAllCompare: function getAllCompare() {
    const query = 'SELECT * FROM ' + tableName + ' ORDER BY lastupdate DESC';
    return db.runCommand(query, null);
  }
};

module.exports = CompareRepository;

Utils

exports.errorFormatter = function(e) {
    let message = '';
    if (e.message) {
        message = e.message;
    } else if (e.stack) {
        message = e.stack;
    } else {
        message = JSON.stringify(e);
    }
    console.log('errMsg', message);
    return new Error(message);
};
Responses