UNPKG

2.11 kBtext/coffeescriptView Raw
1require "coffee-script"
2require "sugar"
3require "../initializer"
4
5Mincer = require "mincer"
6path = require "path"
7fs = require "../utils/my-fs"
8Express = require "express"
9Minimatch = require "minimatch"
10Config = require "../config"
11
12module.exports = class Server
13
14 constructor: (file) ->
15 @config = new Config(file)
16 @app = Express()
17
18 useRewrite: () ->
19 @app.use (req, res, next) =>
20 rewriteRoot = @config.serverRoot
21 isIgnore = false
22 for ignorePath in @config.rewrite.ignorePaths
23 isIgnore = Minimatch(req.url, path.join(rewriteRoot, ignorePath))
24 if isIgnore
25 break
26
27 unless isIgnore
28 for rewrite in @config.rewrite.paths
29 keys = Object.keys(rewrite)
30 rewriteRegex = keys[0]
31 rewritePath = rewrite[rewriteRegex]
32 isRewrite = Minimatch(req.url, path.join(rewriteRoot, rewriteRegex))
33 if isRewrite
34 rewritePath = path.join(rewriteRoot, rewritePath)
35 Mincer.logger["info"]("rewrite: #{req.url} -> #{rewritePath}")
36 req.url = rewritePath
37 break
38
39 next()
40
41 usePublic: () ->
42 pubRoot = path.join(@config.serverRoot, @config.public.contextRoot)
43 for pubPath in @config.public.paths
44 pubPath = path.join(@config.workDir, pubPath)
45 @app.use(pubRoot, Express.static(pubPath))
46
47 useMincer: () ->
48 assetsRoot = path.join(@config.serverRoot, @config.assets.contextRoot)
49 server = new Mincer.Server(@config.createEnvironment())
50 console.log "assetsRoot: [" + assetsRoot + "]"
51 @app.use assetsRoot, (req, res) =>
52 server.handle(req, res)
53
54 start: (callback) ->
55 @process = @app.listen(@config.port, (err) =>
56 if err
57 console.error("Failed start server: " + (err.message || err.toString()))
58 process.exit(128)
59
60 console.info("Listening on localhost:#{@config.port}")
61 console.info()
62
63 if callback? then callback()
64 )
65
66 stop: (callback) ->
67 if not @isRunning() then throw new Error("not running server.")
68 @process.close(callback)
69 @process = null
70
71 isRunning: () ->
72 @process?
73