-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.coffee
More file actions
93 lines (74 loc) · 1.94 KB
/
base.coffee
File metadata and controls
93 lines (74 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
request = require 'request'
capitalize = require 'capitalize'
plural = require 'plural'
credentials = require './credentials'
class Base
constructor: (@options)->
if @belongs_to?
@establish_belongs_to()
route: (ex, qs)->
@resource
url: (uri) ->
env = process.NODE_ENV
if env
env = env.toLowerCase()
if not env or env is 'development'
host = 'http://localhost'
port = '3000'
else
console.log 'Client running in production mode'
throw new Error """
We are not ready to target anything but development
"""
s = "#{host}"
if port
s += ":#{port}"
if uri
s += "/#{uri}"
return s
req_options: (uri, body) ->
url: @url uri
json: true
body: body if body
hawk:
credentials: credentials.get() if credentials.get()
request: (method, uri, body, cb) ->
fun = request[method]
if !fun
throw new Error "Request doesn't have #{method} defined"
if typeof fun isnt 'function'
throw new Error "Request #{method} is not a function"
if typeof body is 'function'
cb = body
body = null
options = @req_options uri, body
fun options, (err, res, resBody)->
cb res, resBody
handler: (verb, path, ops, cb) ->
if typeof ops is 'function'
cb = ops
ops = null
@request verb, path, ops, (res, body)->
if res.statusCode is 200
cb null, body
else
cb {
statusCode: res.statusCode
message: body.error
}
###
# Relationship logic
###
establish_belongs_to:()->
@["getFor#{capitalize @belongs_to}"] = (id, cb) =>
@handler "get", "#{plural @belongs_to, 2}/#{id}/#{@resource}", cb
###
# CRUD functionality
###
create: (ops, cb)->
@handler "post", @route(), ops, cb
delete: (id, cb)->
@handler "del", "#{@route()}/#{id}", cb
get: (id, cb) ->
@handler "get", "#{@route()}/#{id}", cb
module.exports = Base