ExamplesToggle endpoint state (JavaScript)

Toggle endpoint state (JavaScript)

The following code example toggles the state of an endpoint by ID:

function toggleStatus(endpointId) {
const baseUrl = 'cdn.emnify.net';
const token = 'AUTH_TOKEN';
const headers={
'Accept':'application/json',
'Authorization': `Bearer ${token}`
}
fetch(`${baseUrl}api/v1/endpoint/${endpointId}`, {
method: 'GET',
headers: new Headers(headers)
})
.then(response => response.json())
.then(endpoint => {
// The endpoint status is retrieved as an object {id: 0, description: "Enabled"}
// and should be set as an object without a description
// Available statuses:
// 0 - Enabled
// 1 - Disabled
const status = endpoint.status.id == 1 ? { id: 0 } : { id: 1 };
return fetch(`${baseUrl}api/v1/endpoint/${endpointId}`, {
method: 'PATCH',
headers: new Headers({
'Content-Type':'application/json;charset=UTF-8',
...headers
}),
body: JSON.stringify({ status })
})
})
.then(console.log)
.catch(console.error)
}