"Received unknown parameter: lines" (Stripe API Error) - javascript

I'm trying to add multiple invoice items inside one invoice object with Stripe.
Here is my code :
// // create stripe invoice
const invoice = await stripe.invoices.create({
customer: customerId,
collection_method: "send_invoice",
days_until_due: 30,
// for each reloadItem, create an invoice item
lines: {
object: "list",
data: reloadItems.map((reloadItem) => {
return {
price: stripePrice.id,
quantity: reloadItem.quantity,
};
}),
}
});
console.log({ invoice });
Here is the documentation I'm using : https://stripe.com/docs/api/invoices/object
I'm not sure why I receive the error "Received unknown parameter: lines", is it the code ? Or is the API Documentation not updated ?

Related

How to post the JSON data in a embed in discord.js

I wrote a code and i got the data in a json format. Now i want it to convert that data into a discord embed so that when i enter a command . EX:- .data the json data to be sent from the URL.
Here is the input
request({
url: "https://data.vatsim.net/v3/vatsim-data.json",
json: true
}, (err, response, body) => {
console.log(body)
})
The json data looks like this :
{
cid: 1435807,
name: ' ',
callsign: 'ZAP85LJ',
flight_plan: [Object],
last_updated: '2021-10-24T10:45:52.516736Z'
},
{
cid: 1439854,
name: ' ',
callsign: 'DLH1ML',
flight_plan: [Object],
last_updated: '2021-10-24T10:46:13.4226778Z'
}
You can use EmbedFields, you can use up to 25 fields on an embed. On this example I used .forEach so that for each element on the array I can create a field with its value:
request({
url: "https://data.vatsim.net/v3/vatsim-data.json",
json: true
}, (err, response, body) => {
const embed = new Discord.MessageEmbed()
const pilots = body.pilots.slice(0, 15)
body.pilots.forEach(pilot => {
embed.addField(p.name,
`CID : ${p.cid}
Server : ${p.server}
etc...`)
})
message.channel.send(embed)
}
If you really want to show every single one of your elements on the array you can use discord-buttons to make the embed edit its message and change pages but for now this is the simplest and easiest solution for you.

Parse JSON Object from MongoDB GET

I have a ReactApp with a MongoDB based on local events here in my city. The current schema looks like this.
const eventSchema = mongoose.Schema({
start: String,
end: String,
name: String,
loc: { // Reference: https://mongoosejs.com/docs/geojson.html
type: {
type: String,
enum: ['Point']
},
coordinates: {
type: [Number]
}
},
web: String,
desc: String
});
I have an event button where I press, it gets the data from the DB and renders it to the HTML Page
callbackGetData() {
fetch('/api')
.then(resp => {
console.log(resp);
return resp.json();
})
.then(jdat => {
console.log(jdat);
this.setState({ data: JSON.stringify(jdat)}); // Print to debug area.
// todo: Update marker on the map?
});
}
when printed on the screen, this the results from the JSON objects that are stored in the database
[{"loc":{"coordinates":[-122.698687,45.526974],"type":"Point"},"_id":"5e5c3cde56138449ec49905f","start":".","end":".","name":"Portland Dining Month","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.680712,45.509871],"type":"Point"},"_id":"5e5c3cde56138449ec499060","start":".","end":".","name":"Test event #PSU","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.674043,45.481716],"type":"Point"},"_id":"5e5c3cde56138449ec499057","start":".","end":".","name":"Transgender Clients: Assessment and Planning for Gender-affirming Medical Procedures","web":".","desc":".","__v":0}]
If I try to go and print it with
console.log(jdat);
this.setState({ data: JSON.stringify(jdat.name)});
It says that it undefined. How can I go about printing out just the individual names and location coordinates and storing them in a variable I can use elsewhere in the file? Thanks
Looks like you have a array of data coming from database. so trying jdat.name will not work. You need to iterate over the array.
try the following code.Hope you are looking for the same
var jdat = [{"loc":{"coordinates":[-122.698687,45.526974],"type":"Point"},"_id":"5e5c3cde56138449ec49905f","start":".","end":".","name":"Portland Dining Month","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.680712,45.509871],"type":"Point"},"_id":"5e5c3cde56138449ec499060","start":".","end":".","name":"Test event #PSU","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.674043,45.481716],"type":"Point"},"_id":"5e5c3cde56138449ec499057","start":".","end":".","name":"Transgender Clients: Assessment and Planning for Gender-affirming Medical Procedures","web":".","desc":".","__v":0}]
jdat.forEach(item =>{
console.log("Name : ",item.name)
console.log("Location Coordinates : ",item.loc.coordinates)
})

Dealing with JSON data returned from a DynamoDB query

I am storing data in a DynamoDb table. I have 3 columns:
hub_id (edit: primary partition key)
on_time (sort key - this is a date time stored as a string)
details this contains my JSON data (information from a sensor):
{ "hub_id" : { "S" : "PnKVrm12" }, "temperature" : { "S" : "23" }, "sensor_name" : { "S" : "Tech Lab" }}
Using react-native and aws amplify I can query the table using the following code and return the correct number of rows :
// setup query params
var params = {
TableName : "hiddenprojectv-mobilehub-1542262168-hidden",
ProjectionExpression:"hub_id, details.temperature, details.sensor_name",
KeyConditionExpression: "hub_id = :hid",
ExpressionAttributeValues: {
":hid":"PnKVrm12"
}
};
//execute query using params
db.query(params, function(err, data) {
if (err) {
console.log("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
data.Items.forEach(function(details) {
console.log(details.hub_id,details.sensor_name);
});
}
});
but I am struggling to get at the data held in the Json object (details column). The query above returns:
16:44:45: PnKVrm12 undefined
I expected it to return:
16:44:45: PnKVrm12 Tech Lab
for some reason I can never access data in either temperature or sensor_name.
I would appreciate some advice if you have time.
Your ProjectionExpression is accessed in your forEach loop and provides:
details = { hub_id: 'x', details: { temperature: 'x', sensor_name: 'x' } };
You are not using your data structure properly. To access the sensor_name property you must use:
`details.details.sensor_name'

mongodb array data store using node js

I have to try to store my child info into MongoDB via using postman tool. But it shows me this message "message": "child info validation failed"
in postman console. child info is my collection name where I store my child info.
my requirement is to store the result in array form as below schema mentioned inside MongoDB
1). This is js child schema
userId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
quiz:[
{
questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'questions'
},
score:{type:String},
time:{type:String}
}
]
2). This is node js
try {
var quizArr = [];
var quizObj = {
'questionId': req.params.questionId,
'score': req.params.score,
'time': new Date().toISOString()
};
quizArr.push(quizObj);
var userObj = {
'userid': req.params.userId,
'quiz': quizArr
};
//var parseObj = Json.stringify(userObj); This line is comment
var childinfoSave = new QuizChildInfo(userObj);
childinfoSave.save(function (err) {
if (err) return next(err);
res.send("Child questionId score and date saved successfully")
console.log("Child questionId score and date saved successfully");
});
}catch(err){console.log(err);}
3). Output of postman screen
{
"message": "childinfos validation failed"
}
4). Output of console
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
5). Mongo console
{
"_id" : ObjectId("57bc483169e718642ac0ac44"),
"levelsAttempted" : [ ],
"quiz" : [ ],
"__v" : 0
}
For the problem of your console,
put mongoose.Promise = global.Promise; in the file where you have established your server connection( like in my case its index.js).
And i think you may have not posted the whole code as i couldnt find childinfos in your code.

How to improve or avoid find / fetch cycle in meteor's publication?

TL;DR:
Chat is one collection. ChatMess another one that has messages refering to a Chat's _id. How do I get the last messages from a list of chats with the less computation possible ? Here, find / fetch cycle in a loop is way too heavy and long.
I have this publication that is used to return a set of cursor to the user :
The chats sessions he takes part in (from Chat collection)
The last message from each of the chat session referenced in the first cursor (from ChatMess collection)
Currently, the logic is to :
Get the list of chat sessions from the user profile
Find the Chat sessions and loop through it
In the loop, I findOne the last message from this chat session and store its _id in an array. In addition, I store all the other users _ids.
Then, I find the messages which _id match the ones in my array.
Here is my main problem :
Isn't there a way more faster way to get the last messages from each of my chat session ? With that algo, I easily reach the 8000ms of response time, which is a way too heavy computation time, as much of this time is spent to find / fetch the chat messages's _id (cf linked screen from Kadira).
Meteor.publish("publishNewChat", function() {
this.unblock();
// we get a list of chat _id
let chatIdList = _get_all_the_user_chats_ids(this.userId);
if (!chatList)
return ;
// get the chat sessions objects
let chats_cursor = Modules.both.queryGet({
type : 'chat',
method : 'find',
query : { _id: { $in: chatIdList } },
projection : { sort: { _id: 1 }, limit : 1000 }
});
let array_of_fetched_chats = chats_cursor.fetch();
let chat_ids = [];
// and here we loop through the chat documents in order to get the last message that's been attached to each of them
array_of_fetched_chats.forEach(function(e) {
let lastMess = Modules.both.queryGet({
type : 'chatMess',
method : 'findOne',
query : { chatId: e._id },
projection : { sort: { date: -1 } }
});
if (lastMess)
chat_ids.push(lastMess._id);
});
return ([
chats_cursor,
Modules.both.queryGet({
type : 'chatMess',
method : 'find',
query : { _id: { $in: chat_ids } },
projection : { sort: { date: -1 }, limit: 1000 }
})
]);
});
Finally, it also add latence to all my DDP request that follows. I currently use a this.unblock() to avoid that, but I'd prefer not to use it here.
FYI, I have another publish that is updated each time the client change his current active chat session : on the client, routing to a new chat add its _id in a reactive array that update my getChatMess subscription in order to get on the client the messages from every chats the user visited in this since he connected. The goal is obviously to spare the server the sending of every message from every chat session the user have visited in his life.
Unfortunately, I lack ideas to improve that algo without breaking all my chat logic :S. Have you any idea ? How would you do ?
Thanks you.
EDIT: here is a screen from kadira that clearly show the problem :
Have you considered using the reywood/publishComposite package?
With this package you can publish related data in the same method without having to do a bunch of logic to get the correct data published.
The below code should get you started:
Meteor.publishComposite("publishNewChat", function() {
return [{
find:function(){
return Users.find({ _id: this.userId },{fields:{"profile.chat":1}});
},
children:[{
find:function(user){ //this function is passed each user returned from the cursor above.
return UserChats.find({userId:user._id},{fields:{blah:1,blah:1}}); //find the user chats using whatever query
},
children:[
//if there are any children of user chats that you need to publish, do so here...
{
find:function(userchat){
return Chats.find({_id:userchat.chatId})
},
children:[
{
find:function(chat){
return ChatMess.find({chatId:chat._id},{ sort: { date: -1 } });
},
children:[
{
find:function(chatMess){
var uids = _.without(chatMess.participants, this.userId);
return Users.find({_id:{$in:uids}});
}
}
]
}
]
}
]
},
]
}]
This will publish the cursors for all of the documents related to each of the parent documents. It is pretty fast, I use this package on a production platform high traffic and large datasets with no problems. On the client you could then query the documents as normal to get the ones you need to display.
Something like:
Users.findOne({_id:Meteor.userId()});
UserChats.find({userId:Meteor.userId()});
etc...
Here is a solution I developped :
Meteor.publish("publishNewChat", function() {
this.unblock();
let user = Modules.both.queryGet({
type : 'users',
method : 'findOne',
query : { _id: this.userId },
projection : { fields: { "profile.chat": true } }
});
let thisUserschats = tryReach(user, "profile", "chat").value;
if (!thisUserschats)
return ;
thisUserschats = thisUserschats.map(function(e) { return (e.chatId); });
let chats = Modules.both.queryGet({
type : 'chat',
method : 'find',
query : { _id: { $in: thisUserschats } },
projection : { sort : { _id: 1 },
limit : 1000
}
});
let chatArray = chats.fetch(),
uids = cmid = [];
let messages_id_list = [],
i = chatArray.length;
let _parallelQuery = index => {
Meteor.setTimeout(function () {
let tmp = Modules.both.queryGet({
type : 'chatMess',
method : 'find',
query : { chatId: chatArray[index]._id },
projection: { limit: 1, sort: { date: -1 } }
});
tmp.forEach(doc => {
messages_id_list.push((doc && doc._id) ? doc._id : null);
});
}, 1);
}
while (--i >= 0)
_parallelQuery(i);
let cursors = {
chats : chats,
chatMessages : null
}
let interval = Meteor.setInterval(function () {
if (messages_id_list.length === chatArray.length)
{
Meteor.clearInterval(interval);
cursors.chatMessages = Modules.both.queryGet({
type : 'chatMess',
method : 'find',
query : { _id: { $in: messages_id_list } },
projection : { sort: { date: -1 }, limit: 1000 }
});
cursors.chats.observeChanges({
// ...
});
cursors.chatMessages.observeChanges({
// ...
});
self.ready();
self.onStop(() => subHandle.stop(); );
}
}, 10);
});
I used async function with Meteor.setTimeout to parallelize the queries and save an index refering to a chat _id to look for. Then, when a query is finished, I add the last message to an array. With a Meteor.setInterval, I check the array length to know when all the queries are done. Then, as I can't return cursors anymore, I use the Meteor publication low level API to handle the publishing of the documents.
FYI : in a first attempt, I was using 'findOne' in my _parallelQueries, which divided my computation time by 2/3. But then, thanks to a friend, I tried the cursor.foreach() function, which allowed me to divide the computation time by 2 again !
In production, the benchmarks allowed me to go from a 7/8 second response time to an average response time of 1.6 second :)
Hope this will be usefull to you people ! :)

Categories