|
| 1 | +import * as path from "path"; |
| 2 | +import * as express from "express"; |
| 3 | +import * as bodyParser from "body-parser"; |
| 4 | +import * as serveStatic from "serve-static"; |
| 5 | + |
| 6 | +import { Netlify } from "./netlify"; |
| 7 | + |
| 8 | +export class Server { |
| 9 | + public express: express.Express; |
| 10 | + public paths: Server.Paths; |
| 11 | + |
| 12 | + constructor( |
| 13 | + private netlifyConfig: Netlify.Config, |
| 14 | + private port: number, |
| 15 | + ) { |
| 16 | + this.initialize(); |
| 17 | + } |
| 18 | + |
| 19 | + public initialize (): void { |
| 20 | + this.paths = { |
| 21 | + static: path.join(process.cwd(), this.netlifyConfig.build.publish), |
| 22 | + lambda: path.join(process.cwd(), this.netlifyConfig.build.functions), |
| 23 | + } |
| 24 | + this.express = express(); |
| 25 | + this.express.use(bodyParser.raw()); |
| 26 | + this.express.use(bodyParser.text({type: "*/*"})); |
| 27 | + this.express.use(serveStatic(this.paths.static)) |
| 28 | + this.routeLambdas(); |
| 29 | + this.routeRedirects(); |
| 30 | + } |
| 31 | + |
| 32 | + private routeRedirects (): void { |
| 33 | + for(const redirect of this.netlifyConfig.redirects) { |
| 34 | + this.handleRedirect(redirect.from, redirect.to); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public handleRedirect(from: string, to: string): void { |
| 39 | + this.express.get(from, (request, response, next) => { |
| 40 | + return response.status(200).sendFile(path.join(this.paths.static, to)); |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + private routeLambdas (): void { |
| 45 | + this.express.all("/.netlify/functions/*", this.handleLambda()); |
| 46 | + } |
| 47 | + |
| 48 | + private handleLambda (): express.Handler { |
| 49 | + return (request, response, next) => { |
| 50 | + response.status(200).json("lambda!"); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public listen (): void { |
| 55 | + this.express.listen(this.port, (error: Error) => { |
| 56 | + if (error) { |
| 57 | + console.error("netlify-local: unable to start server"); |
| 58 | + console.error(error); |
| 59 | + process.exit(1); |
| 60 | + } |
| 61 | + |
| 62 | + console.log(`netlify-local: server up on port ${this.port}`); |
| 63 | + }); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export namespace Server { |
| 68 | + export interface Paths { |
| 69 | + static: string; |
| 70 | + lambda: string; |
| 71 | + } |
| 72 | +} |
0 commit comments