Hello!
Apologies if this is already documented/answered somewhere. Feel free to point me to that if that’s true. I tried to use by basic search skills, but that did not yield any useful results.
Coming to the actual question, my use case is that, I wish to pull data from an API. The API mentions, try not to poll it more than once per 3 days as it won’t update as frequently, and we would be burderning its servers. So, I thought of saving the data in Fauna.
I’m using Netlify Functions (TypeScript) with a Vue frontend, so saving the data in a file is not an option as I’d have to re-deploy the entire site to update the data.
Here’s what I’m planning to do:
Retrieve the document from Fauna → Compare its ts
with Now()
→ If it’s greater than 3 days, pull the data from API and update the document → If not, simply use the data from Fauna.
I constructed a basic Query:
Let({
doc: Get(
Ref(
Collection(
'foo'
),
'bar'
)
)}, GTE(
TimeDiff(
Epoch(
Select(
'ts',
Var('doc')
),
'microseconds',
),
Now(),
'days'
),
3
)
)
I stored the document as a variable doc
, because I assumed, I can update the same ref later in the query. My previous query involved me directly using Get()
inside Select()
, thus, avoiding Let()
altogether.
Now my question is, I can use If()
to check the condition as mentioned above. What I don’t know is, if I can use plain JavaScript code (using fetch
or axios
) to pull data from API and update the document in the same query. I can achieve this using standard JavaScript code, like:
db.query(
GTE(
TimeDiff(
Epoch(
Select(
'ts',
Get(
Ref(
Collection(
'foo'
),
'bar'
)
)
),
'microseconds',
),
Now(),
'days'
),
3
)
).then(response => {
if (response) {
// greater than 3 days, need to update
// also query Fauna again to store the updated data
} else {
// less than 3 days, can use that data,
// but now, I'll have to query Fauna again to fetch the document data
}
})
Note, my above code might have syntax errors in the FQL, because I’ve hand-typed it without checking perfectly for bracket closures. I’m just trying to represent what I’m trying to achieve.