Results from query are undefined - javascript

I have been adding custom functionality in Strapi code through the controller.
The below result variable comes up as undefined. If I return the result variable directly in the function the result is correctly returned in the http response. Is there any issues in the syntax below ? I appreciate any help i can get.
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#core-controllers)
* to customize this controller
*/
module.exports = {
async getItemAggregate (context) {
var itemid = context.params.itemid
strapi.log.info(itemid)
strapi.log.info("test aggregate");
const result = await strapi.query('aggregate').findOne({"id": itemid});
strapi.log.info(result)
// const fields = result.toObject();
// strapi.log.info(result)
// entities = await strapi.services.aggregate.search({"id":1});
// entities2 = await strapi.services.item.search({"id":1});
// strapi.log.info(entities)
strapi.log.info(result)
// strapi.log.info(entities2)
//get latest aggregate
//get latest tranacitons
}
};

Had a similar issue. The thing I found out is that strapi.log.<function> doesn't stringify the query. Try logging the query wrapped with JSON.stringify(<query>).
Like this:
const result = await strapi.query('aggregate').findOne({"id": itemid});
strapi.log.info(JSON.stringify(result));

Related

How to add a document with an auto generated ID into a Sub Collection using Firebase

This code works and shows an alert of { "plantID" : "2" }. but when I try to uncomment
const newDoc = await addDoc(userPlants, data);, it doesn't push it to Firebase.
window.onsubmit = async function addPlant(){
// Specify which HTML data to get from
var selectPlants = parseInt(document.getElementById("plantID").value);
// Get reference to the collection that we are adding Data to
const userPlants = collection(firestore, "Users/" + "s6wnGQY3pH3oBGEyNJmZ/" + "Plants");
const data = {
plantID: selectPlants
};
alert(JSON.stringify(data));
//const newDoc = await addDoc(userPlants, data);
}
However, if I changed the code to
async function addPlant(){
// Specify which HTML div to use
var selectPlants = parseInt(document.getElementById("plantID").value);
// Get reference to the collection that we are adding Data to
const userPlants = collection(firestore, "Users/" + "s6wnGQY3pH3oBGEyNJmZ/" + "Plants");
const data = {
plantID: 3
};
const newDoc = await addDoc(userPlants, data);
}
and add it to the window.onload function, it works and stores it in Firebase. I've checked that const data gives the proper value. I have also tried onclick, as well as adding the functions and function call directly in the HTML folder as well, all with no luck.

How to get file that is calling function

I have this global function in my main app file
async getTip(){
const tipschema = require('./schemas/tipschema')
const tipschemas = await tipschema.find()
const randomschema = tipschemas[Math.floor(Math.random()*tipschemas.length)]
const randomtip = randomschema.tip
return randomtip
},
Is there any way I can get the file name that is calling the function?
For example:
async getTip(){
const file = await req.file // example of what I'm trying to do
},
thanks
You can do:
function getTip() {
let caller = getTip.caller;
}
BUT this is depricated. Look also here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
Also note that this is not working with strict mode.

At an object's instantiation time how does one handle best the asynchronous initialization of one of its properties?

I've never created a Javascript module/library before so this is a bit new to me so apologizes for my lack of knowing what to google.
I'm creating a library that will hold information from a URL that is provided by a user. I want to parse the URL's path (the part that comes after the domain) as well as retain a header value that's provided by the URL's response.
It's basic but here's what I have so far:
function Link(someURL) {
this.url = someURL;
this.urlPath = "";
this.uuid = "";
this.getPath = function (someURL) {
// do regexp parsing and return everything after the domain
};
this.getUUID = function (someURL) {
// fetch the URL and return what is in the response's "uuid" header
}
}
Ideally, I'd the module to automatically get all the information upon construction:
var foo = new Link("http://httpbin.org/response-headers?uuid=36d09ff2-4b27-411a-9155-e82210a100c3")
console.log(foo.urlPath); // should return "uuid"
console.log(foo.uuid); // should return the contents in the "uuid" header in the response
How do I ensure the this.urlPath and this.uuid properties get initialized along with this.url? Ideally, I'd only fetch the URL once (to prevent rate limiting by the target server).
After a lot of trial and error, I ended up doing something more like this:
class Link {
constructor (url_in) {
const re = RegExp("^https://somedomain.com\/(.*)$");
this.url = re[0];
this.linkPath = re[1];
}
async getUUID() {
const res = await fetch("https://fakedomain.com/getUUID?secret=" + this.linkPath);
this.uuid = res.uuid;
}
async getJSON() {
const res = await fetch("https://fakedomain.com/getJSON?uuid=" + this.uuid);
this.json = await res.json();
}
async initialize() {
await this.getUUID();
await this.getJSON();
}
}
const someLinkData = new Link("https://reallydumbdomain.com/2020/10/4/blog");
someLinkData.initialize()
.then(function() {
console.log(this.json); // this now works
});
I think a future iteration of this will require me to send a promise with the initialize function but for now, this works.

Flutter Firebase Functions Error: Database not defined

I've created a delete oldFiles function for my Database that deletes nodes from my chat messages. I've used the example function provided by Firebase and updated it to fit my use. My database structure is databaseName/messages/{pushId} and I've added const functions = require('firebase-functions') and const admin = require('firebase-admin') and admin.initializeApp(). Here is what I have...
exports.deleteOldItems = functions.database.ref('messages/{pushId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = (DateTime.now().millisecondsSinceEpoch - CUT_OFF_TIME);
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
When I review my Function logs, I'm getting the following errors...
ReferenceError: DateTime is not defined
at exports.deleteOldItems.functions.database.ref.onWrite (/srv/index.js:17:18)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
And my Functions are finishing with status: error. Any ideas to what may be going on?
DateTime isn't a valid JavaScript object or identifier. If you want to work with dates and times, you will need to work with Date, as you are in the line just above where you have DateTime. You should probably review the JavaScript documentation for Date to learn how it works.

Create global variable in utils.js file in node.js

Hi I'm currently trying to figure it out how to properly define global variable in node.js. I know it is not a good practice to do this, but in this particular screnario it's the only way to do this without using connection to database.
I'm getting data from github API to display some information, I'm trying to store them in the global variable. It should allow me to e.g pass specific object from first global list to new global list that display only chosen items.
I have file called utils.js that have this two empty arrays that should be global:
let repoItems = [];
let bookmarkedItems = [];
exports.repoItems = repoItems;
exports.bookmarkedItems = bookmarkedItems;
Then I have another file that fetch and should assign items to the first global variable, but it looks like it doesn't. Because in the moment I'm trying to chose one item & push it into second empty array it's impossible, I'm getting empty array. I'm not sure if the mistake is taken because of bad implementation of global variable from other file, or something else :/
Below I include the fetching part of code, with bold part that I'm confused with:
let utils = require('../utils');
let {
repoItems,
} = utils;
router.get('/', async (req, res) => {
try {
const result = await fetchGithubAPI(`searching word`);
const urls = result.map(url => url);
console.log(urls);
res.render('repositories.ejs', {
'data': urls
});
} catch (e) {
console.log(e);
}
});
async function fetchGithubAPI(search) {
const response = await fetch(`https://api.github.com/?q=${search}`, {
method: 'GET',
headers: {
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json',
},
});
const data = await response.json();
**repoItems = data.items.map(item => item);**
return repoItems;
}
Try:
let repoItems = require('./utils').repoItems
instead of
let {
repoItems,
} = utils;
if you remove
let {
repoItems,
} = utils;
you can try using
utils.repoItems = data.items.map(item => item)
I tried an example setup for it
--utils.js
module.exports.someValue = 3;
module.exports.setSomeValue = (value) => {someValue = value}
--index.js
const utils = require('./utils');
console.log(utils.someValue);// 3
utils.someValue = 5
console.log(utils.someValue);// 5
Update after knowing about getter and setter methods in Js
You can refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
this is another way to change value of any private properties in JS

Categories

Resources