This repository has been archived by the owner on Jun 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.js
55 lines (49 loc) · 1.56 KB
/
user.js
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
var Promise = require("bluebird");
var request = Promise.promisifyAll(require('request'));
exports.getAgeFromBirthday = getAgeFromBirthday;
exports.parseUser = parseUser;
exports.addFullName = addFullName;
function getUserOverNetwork() {
var requestSettings = {
'url': 'http://gfnork.de/test'
};
return request.postAsync(requestSettings)
.spread(function (httpResponse, body) {
body = JSON.parse(body);
return body.user;
})
.then(parseUser);
}
function addAgeToUser(user) {
return getAgeFromBirthday(user.birthday)
.then(function (age) {
user.age = age;
return user;
});
}
function parseUser(user) {
return addAgeToUser(user)
.then(addFullName);
}
function addFullName(user) {
return new Promise(function (resolve, reject) {
user.longName = user.firstName + ' ' + user.lastName;
resolve(user);
});
}
function getAgeFromBirthday(birthday) {
return new Promise(function (resolve, reject) {
if ((birthday instanceof Date) && birthday != 'Invalid Date') {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // milliseconds from epoch
var age = Math.abs(ageDate.getUTCFullYear() - 1970);
if ((0 <= age) && (age <= 150)) {
return resolve(age);
} else {
return reject('age is not within the valid range')
}
} else {
return reject('parameter birthday is not a valid date');
}
});
}