UNPKG

1.75 kBtext/coffeescriptView Raw
1lazorse = require '../'
2lazorse ->
3 greetingLookup = english: "Hi", french: "Salut"
4
5 # This defines a route that accepts both GET and POST
6 @route "/greeting/{language}":
7 description: "Per-language greetings"
8 shortName: 'localGreeting'
9 GET: -> @ok greeting: greetingLookup[@language], language: @language
10 POST: -> greetingLookup[@language] = @req.body; @ok()
11 examples: [
12 {method: 'GET', vars: {language: 'english'}}
13 {method: 'POST', vars: {language: 'english'}, body: "howdy"}
14 ]
15
16 # Define a coercion that restricts input languages to the
17 # ones we have pre-defined
18 @coerce language: (language, next) ->
19 language = language.toLowerCase()
20 if language not in greetings
21 errName = @req.method is 'GET' and 'NotFound' or 'InvalidParameter'
22 @error errName, 'language', language
23 else
24 next null, language
25
26 # Extend the app with a custom rendering engine
27 # Uses https://github.com/visionmedia/consolidate.js
28 # and a non-standard route property ``view``
29 cons = require 'consolidate'
30 @render 'text/html', (req, res, next) ->
31 res.setHeader 'Content-Type', 'text/html'
32 engine = req.route.view?.engine or 'swig'
33 path = req.route.view?.path or req.route.shortName or 'fallback.html'
34 cons[engine] path, res.data, (err, html) ->
35 if err? then next err else res.end html
36
37 # Define a custom error type and register it with the app
38 TeapotError = -> @code = 418
39
40 @error TeapotError, (err, req, res, next) ->
41 res.end """
42 I'm a little teapot, short and stout.
43 Here is my handle, here is my spout.
44 When I get all steamed up, hear me shout!
45 Tip! me over and pour me out!
46 """
47
48 @route '/teapot': GET: -> @error 'TeapotError'