Skip to content

Commit

Permalink
feat(GlpiRestClient): create basic restclient
Browse files Browse the repository at this point in the history
  • Loading branch information
Gianfranco97 committed Jan 15, 2018
1 parent a16ee18 commit 75168e3
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/GlpiRestClient.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import itemtype from './itemtype.json'
import restclient from './restclient'

export default restclient
export {
itemtype
}
35 changes: 35 additions & 0 deletions src/prepareRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@


function prepareRequest (data) {

let myHeaders = new Headers()
let myInit = { method: data.method }
let url = `${data.url}/${data.endpoint}`

myHeaders.append('Content-Type', 'application/json')

if (data.appToken) {
myHeaders.append('App-Token', data.appToken)
}

if (data.sessionToken) {
myHeaders.append('Authorization', `user_token ${data.sessionToken}`)
}

switch (data.function) {
case 'initSessionByCredentials':
myHeaders.append('Authorization', `Basic ${Buffer.from(`${data.userName}:${data.userPassword}`).toString('base64')}`)
break
default:
break
}

myInit = {
...myInit,
headers: myHeaders
}

return new Request(url, myInit)
}

export default prepareRequest
50 changes: 50 additions & 0 deletions src/restclient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import prepareRequest from './prepareRequest'

class GlpiRestClient {
constructor (url, appToken = '') {
this._url = url
this._sessionToken = ''
this._appToken = appToken
}

get url () {
return this._url
}

set url (url) {
this._url = url
}

get sessionToken () {
return this._sessionToken
}

set sessionToken (sessionToken) {
if (sessionToken) this._sessionToken = sessionToken
}

get appToken () {
return this._appToken
}

set appToken (appToken) {
if (appToken) this._appToken = appToken
}

_makeRequest (myRequest, responseHandler) {
fetch (myRequest)
.then((resp) => {
if (resp.headers.get('Content-Type').indexOf("application/json") >= 0) {
responseHandler(resp.json())
} else {
responseHandler(resp.text())
}
})
.catch((err) => {
responseHandler(err)
})
}

}

export default GlpiRestClient

0 comments on commit 75168e3

Please sign in to comment.