Last active
February 8, 2022 01:01
-
-
Save paul121/26bed0987b73c6886fa3a0743c0f47eb to your computer and use it in GitHub Desktop.
Example node script for making aggregator requests via farmOS.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import client factory method for node. | |
const {client} = require('farmos/dist/cjs/farmOS'); | |
// Create a custom auth method to set the api-key header and farm_id query param. | |
const apiKeyAuth = (request, authOpts = {}) => { | |
request.interceptors.request.use( | |
config => { | |
return { | |
...config, | |
headers: { | |
...config.headers, | |
'api-key': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2NDQyNzM0MzkuMDAyMTc1LCJmYXJtX2lkIjpbXSwiYWxsX2Zhcm1zIjp0cnVlLCJzY29wZXMiOlsiZmFybTpyZWFkIiwiZmFybS5pbmZvIl19.b7arBzMkesSQBbt0UgLNT-up3Ml9_XbevvH61zLfZp0', | |
}, | |
params: { | |
'farm_id': 1, | |
}, | |
}; | |
}, | |
Promise.reject, | |
); | |
return { | |
authorize(apiKey) { | |
// Could use this method to set the api-key header or farm_id query param. | |
}, | |
}; | |
}; | |
// Default token functions. | |
let token; | |
const getToken = () => token; | |
const setToken = (t) => { token = t; }; | |
// Create the client. | |
const host = 'http://localhost/api/v2/farms/relay'; | |
const farm = client(host, { | |
clientId: 'farm', | |
getToken, | |
setToken, | |
auth: apiKeyAuth, | |
}); | |
// Create a log object. | |
let newLog = { | |
type: 'log--activity', | |
attributes: { | |
'name': 'My test log', | |
'status': 'done', | |
} | |
} | |
// Fetch logs. | |
farm.log.fetch('activity') | |
.then(res => console.log(`Have ${res.data.data.length} logs.`)) | |
// Create a log. | |
.then(() => farm.log.send('activity', newLog)) | |
.then(res => { | |
console.log('Created new log:', res.data); | |
return res; | |
}) | |
// Fetch the single log. | |
.then((res) => farm.log.fetch('activity', {id: {$eq: res.data.id}})) | |
.then(res => console.log('Fetched the log by ID:', res.data)) | |
// Fetch logs. | |
.then(() => farm.log.fetch('activity')) | |
.then(res => { | |
console.log(`Have ${res.data.data.length} logs.`); | |
return res; | |
}) | |
// Delete log. | |
.then(res => farm.log.delete('activity', res.data.data[0].id)) | |
.then(() => console.log('Delete the log.')) | |
// Fetch logs. | |
.then(() => farm.log.fetch('activity')) | |
.then(res => console.log(`Now have ${res.data.data.length} logs.`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: