index.js 1.03 KB
Newer Older
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// [START functionsimport]
const functions = require('firebase-functions');
const express = require('express');
const mock = require('./mock/index');

const app = express();
const sendData = (body, req, res) => {
  if (!body) {
    res.send('test');
    return '';
  }
  if (typeof body === 'function') {
    body(req, res);
  }
  res.send(body);
};
app.get('/api', (req, res) => {
  const html = Object.keys(mock).map(url => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
19 20
    const href = url.split(' /')[1];
    return `<li><a href="${href}"><code>${url}</code></a></li>`;
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
21 22 23
  });
  res.send(`<ul>${html.join('')}</ul>`);
});
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
24 25 26
app.get('/', (req, res) => {
  res.send(`<ul><li><a href="api/api"><code>/api</code></a></li></ul>`);
});
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

Object.keys(mock).forEach(url => {
  const body = mock[url];
  const urlParams = url.split(' ');

  const path = urlParams[1];
  const send = (req, res) => {
    sendData(body, req, res);
  };
  if (urlParams[0] === 'GET') {
    app.get(path, send);
  }
  if (urlParams[0] === 'POST') {
    app.post(path, send);
  }
});

exports.api = functions.https.onRequest(app);