generated from kyma-project/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathk8s.js
83 lines (76 loc) · 2.52 KB
/
k8s.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
function Client(apiPrefix, options) {
this.options = { ...options }
this.apiPrefix = apiPrefix
this.groupVersions = {}
this.apply = async function (res) {
let path = await this.resPath(res)
path += '?fieldManager=kubectl&fieldValidation=Strict&force=false'
let o = {
...this.options,
method: 'PATCH',
body: JSON.stringify(res),
}
o.headers= {...o.headers, 'content-type': 'application/apply-patch+yaml' }
let response = await fetch(this.apiPrefix + path,o )
await response.text()
console.log(res.kind,res.metadata.name,response.status<300 ? 'applied' : `error:${response.status}` )
return response
}
this.resPath = async function (r) {
let url = (r.apiVersion === 'v1') ? '/api/v1' : `/apis/${r.apiVersion}`
let api = this.groupVersions[r.apiVersion]
let resource = null
if (api) {
resource = api.resources.find((res) => res.kind == r.kind)
}
if (resource == null) {
api = await this.cacheAPI(r.apiVersion)
resource = api.resources.find((res) => res.kind == r.kind)
}
if (resource) {
let ns = r.metadata.namespace || 'default'
let nsPath = resource.namespaced ? `/namespaces/${ns}` : ''
return url + nsPath + `/${resource.name}/${r.metadata.name}`
}
return null
}
this.get = function (path) {
return fetch(this.apiPrefix + path,{
method: 'GET',
...this.options
}).then((res) => {
if (res.status == 200) {
return res.json()
}
return undefined
}).catch((e) => {
return undefined
})
}
this.deleteResource = async function (pathOrResource) {
if (typeof pathOrResource === 'string' || pathOrResource instanceof String) {
return fetch(this.apiPrefix + pathOrResource, { method: 'DELETE', ...this.options })
}
else {
let path = await this.resPath(pathOrResource)
return fetch(this.apiPrefix + path, { method: 'DELETE', ...this.options })
}
}
this.patchResource = function (path, body) {
fetch(this.apiPrefix + path, { method: 'PATCH', headers: { 'content-type': 'application/json-patch+json' }, body, ...this.options })
}
this.cacheAPI = async function (apiVersion) {
let url = (apiVersion === 'v1') ? '/api/v1' : `/apis/${apiVersion}`
let res = await fetch(this.apiPrefix + url,{
method: 'GET',
...this.options
})
if (res.status == 200) {
let body = await res.json()
this.groupVersions[apiVersion] = body
return body
}
return { resources: [] }
}
}
export { Client }