-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandleRequestAction.js
More file actions
88 lines (82 loc) · 2.49 KB
/
Copy pathhandleRequestAction.js
File metadata and controls
88 lines (82 loc) · 2.49 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
const ora = require("ora")
const parseLinkHeader = require("parse-link-header")
const mapItems = require("./mapItems")
const resourcePrompt = require("./prompts/resourcePrompt")
const client = require("./client/client")
const handlers = [
{
test: {
"content-type": "application/json",
"x-github-media-type": "github.v3; format=json"
},
handle(response) {
const { handleResponse } = require("../restlr-plugin-github")
return handleResponse(response)
}
}
]
function transformResponse(headers) {
for (let i=0; i<handlers.length; ++i) {
const handler = handlers[i]
if (Object.keys(handler.test).every(header => {
const value = headers[header] || ""
return value.match(handler.test[header])
})) {
return handler.handle
}
}
return (response) => response
}
async function handleRequestAction(request) {
const { method = "get", href, form, type } = request
const spinnerText = `${method.toUpperCase()} ${href}...`
const spinner = ora(spinnerText).start()
/*const stillTrying = cpromise(
waitp(3000,
spinnerText + " Still trying",
"yellow")
.then(([text, color]) => {
spinner.color = color
spinner.text = chalk[color](text)
}).catch(() => {})
)*/
try {
//await waitp(5000)
const response = await client[method.toLowerCase()](href, {
headers: {
"accept": type
},
form
})
//stillTrying.cancel()
spinner.succeed(`${method.toUpperCase()} ${href} ${response.statusCode} ${response.statusMessage}`)
//console.log(response.headers["content-type"])
if (response.statusCode === 201) {
if (response.headers.location/* && options.followLocationHeader*/) {
return {
request: {
href: response.headers.location
}
}
} else {
console.log("201 Response did not contain Location header.")
}
}
const json = transformResponse(response.headers)(JSON.parse(response.body || "{}"))
console.log(mapItems(json.properties || {}, (value, key) => `${key}: ${value}`).join("\n"))
const headerLinks =
Object.values(parseLinkHeader(response.headers.link) || {})
.map(({url:href, rel}) => ({
href,
rel: [rel]
}))
json.links = (json.links || []).concat(headerLinks)
return {
prompt: resourcePrompt(json, response.headers.location, request)
}
} catch (e) {
spinner.fail(e.message)
throw e
}
}
module.exports = handleRequestAction