/
dataUtils.service.coffee
68 lines (59 loc) · 2.52 KB
/
dataUtils.service.coffee
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
class DataUtils extends Service
constructor: (SPECIFICATION) ->
return new class dataUtilsService
# capitalize first word
capitalize: (string) ->
string[0].toUpperCase() + string[1..].toLowerCase()
# returns the type of the endpoint
type: (arg) ->
a = @copyOrSplit(arg)
a = a.filter (e) -> e isnt '*'
# if the argument count is even, the last argument is an id
if a.length % 2 is 0 then a.pop()
a.pop()
# singularize the type name
singularType: (arg) ->
@type(arg).replace(/s$/, '')
socketPath: (arg) ->
a = @copyOrSplit(arg)
# if the argument count is even, the last argument is an id
stars = ['*']
# is it odd?
if a.length % 2 is 1 then stars.push('*')
a.concat(stars).join('/')
restPath: (arg) ->
a = @copyOrSplit(arg)
a = a.filter (e) -> e isnt '*'
a.join('/')
endpointPath: (arg) ->
# if the argument count is even, the last argument is an id
a = @copyOrSplit(arg)
a = a.filter (e) -> e isnt '*'
# is it even?
if a.length % 2 is 0 then a.pop()
a.join('/')
copyOrSplit: (arrayOrString) ->
if angular.isArray(arrayOrString)
# return a copy
arrayOrString[..]
else if angular.isString(arrayOrString)
# split the string to get an array
arrayOrString.split('/')
else
throw new TypeError("Parameter 'arrayOrString' must be a array or a string, not #{typeof arrayOrString}")
unWrap: (data, path) ->
type = @type(path)
type = SPECIFICATION[type]?.restField or type
data[type]
parse: (object) ->
for k, v of object
try
object[k] = angular.fromJson(v)
catch error then # ignore
return object
numberOrString: (str = null) ->
# if already a number
if angular.isNumber(str) then return str
# else parse string to integer
number = parseInt str, 10
if !isNaN(number) then number else str