-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
109 lines (89 loc) · 2.46 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import 'isomorphic-fetch'
global.apis = {}
function generateApi(name, options) {
let defaults = {
port: 80,
host: '/',
protocol: 'http',
endpoint: 'api'
}
options = Object.assign(defaults, options, {})
return async function(endpoint, method, data) {
options.method = method
switch(method) {
case 'POST':
options.body = JSON.stringify(data)
options.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
break;
case 'GET':
if(typeof data !== 'undefined') endpoint = endpoint + '/' + data
break;
}
let fullEndpoint = `${options.protocol}://${options.host}:${options.port}/${options.endpoint}/${endpoint}?_format=json`
//console.log('options: ', options)
return await fetch(fullEndpoint, options)
}
}
function generateGetApi(options) {
let defaults = {
port: 80,
host: '/',
protocol: 'http',
endpoint: 'api',
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
let merged = Object.assign(defaults, options, {})
String.prototype.get = async function(endpoint) {
let options = merged
let fullEndpoint = `${options.protocol}://${options.host}:${options.port}/${options.endpoint}/${this}/${endpoint}?_format=json`,
response = await fetch(fullEndpoint, defaults)
return await response.json()
}
}
function generatePostApi(options) {
let defaults = {
port: 8000,
host: 'localhost',
protocol: 'http',
endpoint: 'api',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
let merged = Object.assign(defaults, options, {})
String.prototype.post = async function(obj){
let options = merged
options.body = JSON.stringify(obj)
let fullEndpoint = `${options.protocol}://${options.host}:${options.port}/${options.endpoint}/${this}?_format=json`.replace('undefined', '');
let response = await fetch(fullEndpoint, options)
return await response.json()
}
}
function api(api) {
var self = this;
return {
get: async function(slug) {
return await global.apis[api](self, 'GET', slug)
},
post: async function(body) {
return await global.apis[api](self, 'POST', body)
}
}
}
String.prototype.api = api
export function makeApi(name, options) {
global.apis[name] = generateApi(name, options)
}
export function makeShortApi(options) {
generateGetApi(options)
generatePostApi(options)
}