index.js 959 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // [START functionsimport]
  2. const functions = require('firebase-functions');
  3. const express = require('express');
  4. const mock = require('./mock/index');
  5. const app = express();
  6. const sendData = (body, req, res) => {
  7. if (!body) {
  8. res.send('test');
  9. return '';
  10. }
  11. if ('$body' in body) {
  12. res.send(body.$body);
  13. return;
  14. }
  15. if (typeof body === 'function') {
  16. body(req, res);
  17. }
  18. res.send(body);
  19. };
  20. app.get('/api', (req, res) => {
  21. const html = Object.keys(mock).map(url => {
  22. return `<li><code>${url}</code></li>`;
  23. });
  24. res.send(`<ul>${html.join('')}</ul>`);
  25. });
  26. Object.keys(mock).forEach(url => {
  27. const body = mock[url];
  28. const urlParams = url.split(' ');
  29. const path = urlParams[1];
  30. const send = (req, res) => {
  31. sendData(body, req, res);
  32. };
  33. if (urlParams[0] === 'GET') {
  34. app.get(path, send);
  35. }
  36. if (urlParams[0] === 'POST') {
  37. app.post(path, send);
  38. }
  39. });
  40. exports.api = functions.https.onRequest(app);