-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.code.js
84 lines (70 loc) · 2.04 KB
/
example.code.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
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
import { config } from '../App.config';
import { AsyncStorage } from 'react-native';
import store from 'react-native-simple-store';
import * as constants from '../common/constants';
const baseHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
const createService = (postfixUrl, endpoint, method, data) => {
return new Promise((resolve, reject) => {
store.get(constants.USER_INFO).then((storedInfo) => {
const { accessToken, id } = storedInfo;
const authHeaders = {
'FbAuthorization': accessToken,
'UserId': id
}
const options = {
method: method,
headers: {
...baseHeaders,
...authHeaders,
},
};
if(data){
const body = JSON.stringify(data);
options.body = body;
}
const request = new Request(
`${config.apiUrl}${postfixUrl}/${endpoint}`,
{ ...options }
);
return fetch(request).then(resp => {
resolve(resp.json())
}).catch(err => {
reject(err)
})
}).catch(err => {
reject(err)
})
};
})
export const httpService = (postfixUrl) => {
return {
get: (endpoint) => {
return createService(postfixUrl, endpoint, 'GET');
},
post: (endpoint, data) => {
return createService(postfixUrl, endpoint, 'POST', data);
}
}
}
/* Example Usage
post to items/like
post to items/dislike
*/
import { httpService } from './httpService';
const postfixUrl = '/items';
const http = httpService(postfixUrl);
export const likeDislikeItem = (itemId, isLiked) => {
if (isLiked) {
http.post('like', itemId).then(res => {
console.log(res)
});
}
else {
http.post('unlike', itemId).then(res => {
console.log(res)
});
}
}