|
| 1 | +/* Express App */ |
| 2 | +import express from 'express' |
| 3 | +import cors from 'cors' |
| 4 | +import morgan from 'morgan' |
| 5 | +import bodyParser from 'body-parser' |
| 6 | +import compression from 'compression' |
| 7 | +import customLogger from '../utils/logger' |
| 8 | + |
| 9 | +export default function expressApp(functionName) { |
| 10 | + /* My express App */ |
| 11 | + const app = express() |
| 12 | + const router = express.Router() |
| 13 | + router.use(compression()) |
| 14 | + |
| 15 | + // Set router base path for local dev |
| 16 | + const routerBasePath = (process.env.NODE_ENV === 'dev') ? `/${functionName}` : `/.netlify/functions/${functionName}/` |
| 17 | + |
| 18 | + /* define routes */ |
| 19 | + router.get('/users', (req, res) => { |
| 20 | + res.json({ |
| 21 | + users: [{ |
| 22 | + name: 'steve' |
| 23 | + }, { |
| 24 | + name: 'joe', |
| 25 | + }] |
| 26 | + }) |
| 27 | + }) |
| 28 | + |
| 29 | + router.get('/', (req, res) => { |
| 30 | + console.log('home route hit') |
| 31 | + const html = ` |
| 32 | + <html> |
| 33 | + <head> |
| 34 | + </head> |
| 35 | + <body> |
| 36 | + <h1> |
| 37 | + ⊂◉‿◉つ I'm using Express in a lambda via '${functionName}' |
| 38 | + </h1> |
| 39 | + |
| 40 | + <a href='/.netlify/functions/${functionName}/users'>View users</a> |
| 41 | + </body> |
| 42 | + </html> |
| 43 | + ` |
| 44 | + |
| 45 | + res.send(html) |
| 46 | + }) |
| 47 | + |
| 48 | + router.get('/hello/', function(req, res){ |
| 49 | + res.send('hello world') |
| 50 | + }) |
| 51 | + |
| 52 | + // Attach logger |
| 53 | + app.use(morgan(customLogger)) |
| 54 | + |
| 55 | + // Setup routes |
| 56 | + app.use(routerBasePath, router) |
| 57 | + |
| 58 | + router.use(cors()) |
| 59 | + router.use(bodyParser.json()) |
| 60 | + router.use(bodyParser.urlencoded({ extended: true })) |
| 61 | + |
| 62 | + return app |
| 63 | +} |
| 64 | + |
0 commit comments