Filter elements inside of objects - javascript

Assuming that I have this multiple data and I need to filter set of elements.
How could I only filter the data with only text and createdAt will produce:
[
createdAt: "2021-07-07",
text: "No answer found."
]
Data:
var getMessage = [
0: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:11:51.686Z",
web: {
message: {
text: "Get Started"
}
}
},
1: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:11:53.547Z",
web: {
message: {
text: "Etrt"
}
}
},
2: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:12:07.785Z",
web: {
message: {
text: "No answer found."
}
}
}
];
const findKeywords = "O"
const messageData = getMessage.map(x => x);
const findMessage = messageData.filter(x => x.web.message.text.toLowerCase().includes(findKeywords.toLowerCase()));
console.log(findMessage);

to get specific key value try this
const findMessage = messageData.filter(x => x.web.message.text.toLowerCase().includes(findKeywords.toLowerCase())).map(function (obj) {
return {
createdAt: obj.createdAt,
text: obj.web.message.text
};
});;
console.log(findMessage);

Related

Vue how push object with specific key to array

I'm working on an vue-application where I have a component for driving licenses.
I have the following:
data() {
return {
custom_licenses: [],
basic_licenses: []
}
}
within my methods, I have this:
regular_licenses() {
this.$store.dispatch("license/read").then(response => {
response.licenses.map((license, key) => {
// PUSH LICENSES WITH TYPE 'BASIC' TO this.basic_licenses
// PUSH LICENSES WITH TYPE 'CUSTOM' TO this.custom_licenses
});
});
},
and in my created() i have this:
created() {
this.regular_licenses()
}
The response from my dispatch, returns this:
licenses:
[
{
id: 1,
type: 'basic',
name: 'AMa'
},
{
id: 2,
type: 'basic',
name: 'A2'
},
{
id: 3,
type: 'basic',
name: 'C'
},
{
id: 4,
type: 'custom',
name: 'C1'
},
{
id: 5,
type: 'custom',
name: 'D'
},
and so on...
]
Now I want to loop through the array and separate or push them into custom_licenses and basic_licenses based on the type-attribute - how can I achieve that?
Try this
regular_licenses() {
this.$store.dispatch("license/read").then(response => {
response.licenses.map((license, key) => {
switch (license.type)
case 'basic':
this.basic_licenses.push({ ...license });
break;
case 'custom':
this.custom_licenses.push({ ...license });
break;
});
});
},
Update your Code Block:
response.licenses.map((license, key) => {
// PUSH LICENSES WITH TYPE 'BASIC' TO this.basic_licenses
if(license['type'] == 'basic') {
//deep clone
let tmpLicense = JSON.parse(JSON.stringify(license));
basic_licenses.push(tmpLicense);
} else if(license['type'] == 'custom') {
// PUSH LICENSES WITH TYPE 'CUSTOM' TO this.custom_licenses
//deep clone
let tmpLicense = JSON.parse(JSON.stringify(license));
custom_licenses.push(tmpLicense);
}
});

Fastify schema validation isn't working. Do I have something configured the wrong way?

I'm trying to figure out why the schema validation is not working in Fastify. I have the following code:
const postOptions = {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
parentId: { type: 'number' },
requiredKey: { foo: { type: 'string'} }
}
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'number'},
name: { type: 'string'},
parentId: { type: 'number' }
}
}
}
}
}
fastify.post('/sponsor', postOptions, async (request, reply) => {
console.log(`POST /sponsor called`)
return { id: 2, name: 'Zenotis', parentId: 1 }
})
When I use postman to test it out, I can send any keys and values with the body and it goes through fine. It seems like it's not checking at all. Same thing with response. I'm using Fastify version 2.11.0
Edit: here is the json body I'm sending:
{
"name": "Test",
"parentId": 5555555,
"foo": "bar"
}
Here's what I would expect to fail:
{
"myName": "the field is not name",
"parentID": "The D is capitalized and this is a string",
"bar": "where did this field come from, it's not foo"
}
If I send this body, it goes through fine. How do I configure it to fail in all these cases?
Your schema use has a few fixes to apply:
if you don't set the status code 201, the response schema you set will not work. Use '2xx' or set the right code in the reply object
to remove the field that are not in the schema you need to add additionalProperties
if you don't set the required field in the schema, all the fields are optionals
Here a blocking example:
const fastify = require('fastify')()
const postOptions = {
schema: {
body: {
type: 'object',
additionalProperties: false, // it will remove all the field that is NOT in the JSON schema
required: [
'name',
'parentId',
'requiredKey'
],
properties: {
name: { type: 'string' },
parentId: { type: 'number' },
requiredKey: { foo: { type: 'string' } }
}
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' },
parentId: { type: 'number' }
}
}
}
}
}
fastify.post('/sponsor', postOptions, async (request, reply) => {
console.log('POST /sponsor called')
reply.code(201) // if you don't set the code 201, the response schema you set will not work
return request.body
})
fastify.inject({
method: 'POST',
url: '/sponsor',
payload: {
name: 'Test',
parentId: 5555555,
foo: 'bar'
}
}, (_, res) => {
console.log(res.json())
/* it will print
{
statusCode: 400,
error: 'Bad Request',
message: "body should have required property 'requiredKey'"
}
*/
})

How to query firestore() for graphQL resolver?

I'm combining a GraphQL app with my existing Firebase project and am having a lot of problems getting the queries to correctly get data from the firestore().
So far I have the mutations working correctly, but when I go to query the data I can't get the firestore().get() snapshot into a form that graphQL will recognize.
so far it looks like this:
const {GraphQLObjectType,
GraphQLString,
GraphQLBoolean,
GraphQLFloat,
GraphQLSchema,
GraphQLID,
GraphQLList,
GraphQLNonNull} = require("graphql");
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
//Models
const Room = admin.firestore().collection('room');
const Position = admin.firestore().collection('position');
const Plant = admin.firestore().collection('plant');
const PlantInfo = admin.firestore().collection('plantInfo');
const RoomType = new GraphQLObjectType({
name: "Room",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
description: { type: GraphQLString },
floor: { type: GraphQLString },
building: { type: GraphQLString },
positions: {
type: new GraphQLList(PositionType),
resolve(parent, arg) {
//return _.filter(positions, {inRoomId:parent.id})
return Position.orderByChild('inRoomId').equalTo(parent.id);
}
}
})
});
const PositionType = new GraphQLObjectType({
name: "Position",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
description: { type: GraphQLString },
exposure: { type: GraphQLString },
size: { type: GraphQLString },
inRoom: {
type: RoomType,
resolve(parent, args) {
//return _.find(rooms, {id:parent.inRoomId})
return Room.child(parent.inRoomId);
}
}
})
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
room: {
type: RoomType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
//code to get data from db/othersourse
//return _.find(rooms, {id: args.id});
return Room.child(args.id);
}
},
position: {
type: PositionType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
//code to get data from db/othersourse
//return _.find(positions, {id: args.id})
return Position.child(args.id);
}
},
rooms: {
type: new GraphQLList(RoomType),
resolve(parent, args) {
//return rooms
return Room.get().then(snapshot => {snapshot.forEach(doc => {return doc})})
}
},
positions: {
type: new GraphQLList(PositionType),
resolve(parent, args) {
//return positions
return Position.get().then(doc => console.log(doc)).catch(err => console.log('Error getting document', err));
}
}
}
});
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addRoom: {
type: RoomType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
floor: { type: new GraphQLNonNull(GraphQLString) },
building: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args) {
let room = {
name: args.name,
floor: args.floor,
building: args.building
};
return Room.add(room);
}
},
addPosition: {
type: PositionType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
exposure: { type: new GraphQLNonNull(GraphQLString) },
size: { type: new GraphQLNonNull(GraphQLString) },
inRoomId: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args) {
let position = {
name: args.name,
exposure: args.exposure,
size: args.size,
inRoomId: args.inRoomId
};
return Position.add(position);
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
Under the RootQuery -> Rooms I'm trying to get a graphQL query to return all the rooms in my 'room' collection. I have been able to get it to console.log() a list of documents using:
return Room.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, " => ", doc.data());
But getting this into an array has so far eluded me. Any help is really appreciated.
Seeing as no one was able to answer this, I ended up figuring it out for myself :p
So resolve functions relating to getting a collection of related data for example positions. the following works:
first you need a function to convert the snapshots into an array as this is what graphQL is expecting. This also allows your to seperate the id and add it in with the array item:
const snapshotToArray = (snapshot) => {
var returnArr = [];
snapshot.forEach((childSnapshot)=> {
var item = childSnapshot.data();
item.id = childSnapshot.id;
returnArr.push(item);
});
return returnArr;
};
Next when getting the data you use .get() which returns a promise (and error) which can be passed into the snapshotToArray().
return Position.get().then((snapshot) => {
return snapshotToArray(snapshot);
})
For resolve functions that only call on one dataset for example inRoom. Its similar to the first one except using .where() and seperating the id and data() in the snapshot functions:
return Room.doc(parent.inRoomId).get().then((snapshot) => {
var item = snapshot.data();
item.id = snapshot.id;
return item;
})
Just incase someone else runs into the same problem :)

javascript extend an object not working

Banging my head against the wall and I know it's gotta be something stupid...
I have a basic comment(review)/voting system. I am pulling the reviews from the mongo db and in an asysnc.waterfall function, trying to add the votes to each review. Here is the function that adds the votes:
function(reviews, callback) {
let newReviews = [];
_.forEach(reviews, function(review,idx) {
Vote.find({review:review._id}).exec(function(err1, votes){
if (err1){
callback(err1,null);
}else{
console.log("1: REVIEW - ", review);
review.votes = votes;
console.log("2: VOTES - ", review.votes);
newReviews.push(review);
console.log("3: REVIEW - ", review);
if( newReviews.length == reviews.length ){
callback(null,newReviews);
}
}
});
});
}
The votes item never gets populated even though there's data there. Here's some output from those logging statements:
1: REVIEW - { _id: 5a2086139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b9fd942e50e5b,
provider: 'local',
username: 'xxx',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 57995db6666f1ec6f3750,
slug: 'carmel-city-beach-carmel-by-the-sea-california-united-states',
Name: 'Carmel City Beach' },
totalVotes: 1,
reports:
[ { _id: 5a2087f672107f48dd4ed,
user: 5a15cd47db50942e50e5b,
review: 5a208639c3c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
2: VOTES - [ { _id: 5a26fab26a6f85b39484,
review: 5a20867c3c077e546622,
Type: 'review',
user: 5a15cd4db50942e50e5b,
__v: 0,
updated: 2017-12-05T19:59:46.318Z,
created: 2017-12-05T19:59:46.318Z,
IsVote: true } ]
3: REVIEW - { _id: 5a208676139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b50942e50e5b,
provider: 'local',
username: 'mit',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 579db6666fcec6f3750,
slug: 'carmel-city',
Name: 'Carmel City' },
totalVotes: 1,
reports:
[ { _id: 5a2087b107f48dd4ed,
user: 5a15cfdb50942e50e5b,
review: 5a208673c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
Doesn't make sense that the number 2 item would log correctly, but 3 does not...can anyone help me make sense of this stupid issue? Or is it just me? LOL
As requested, here's the Vote mongoose schema definition:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var config = {
Type: {
type: String
},
IsVote: {
type: Boolean,
default: true
},
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
owner: {
type: Schema.ObjectId
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
review: {
type: Schema.ObjectId,
ref: 'Review'
}
};
var VoteSchema = new Schema(config, {
collection: 'votes'
});
/**
* Hook a pre save method to hash the password
*/
VoteSchema.pre('save', function(next) {
next();
});
VoteSchema.method('toggleVote', function() {
this.IsVote = !this.IsVote;
return this.save();
});
VoteSchema.static('createFromReview', function(reviewId, user) {
return new this({
review: reviewId,
Type: 'review',
user: user
});
});
mongoose.model('Vote', VoteSchema);

How to do mutation on array in Relay?

I want to use mutation in Relay to change an array (not connection). The array is typed GraphQLList in the GraphQL side. The graphql side worked perfectly, but relay side needs dataID for each item in an array. And when I am inserting new item or modifying existing item in the array, there are no dataID provided? What is the right way to do this? By the way, I am using redux to maintain the list, and submit changes via relay at the end.
The schema:
let widgetType = new GraphQLInputObjectType({
name: 'Widget',
fields: () => ({
label: {
type: GraphQLString
},
type: {
type: GraphQLString
},
list: {
type: new GraphQLList(GraphQLString)
},
description: {
type: GraphQLString
},
required: {
type: GraphQLBoolean
}
})
});
let modifyFormMutation = mutationWithClientMutationId({
name: 'ModifyForm',
inputFields: {
id: {
type: new GraphQLNonNull(GraphQLString)
},
name: {
type: new GraphQLNonNull(GraphQLString)
},
userId: {
type: new GraphQLNonNull(GraphQLString)
},
widgets: {
type: new GraphQLList(widgetType)
}
},
outputFields: {
formEdge: {
type: formConnection.edgeType,
resolve: (obj) => {
return {
node: {
id: obj.id,
name: obj.name,
userId: obj.userId,
widgets: obj.widgets
},
cursor: obj.id
};
}
},
app: {
type: appType,
resolve: () => app
}
},
mutateAndGetPayload: ({
id, name, userId, widgets
}) => {
db.collection('forms').findOneAndUpdate({
_id: new ObjectID(id)
}, {
name, userId, widgets, createAt: Date.now()
});
return {
id, name, userId, widgets
};
}
})
Relay mutation:
export default class ModifyFormMutation extends Mutation {
getMutation () {
return Relay.QL`mutation{modifyForm}`;
}
getFatQuery() {
return Relay.QL`
fragment on ModifyFormPayload {
formEdge
app { forms }
}
`;
}
getCollisionKey() {
return `check_${this.props.app.id}`;
}
getConfigs() {
return [{
type: 'FIELDS_CHANGE',
fieldIDs: {
formEdge: {node: this.props.node},
app: this.props.app.id
}
}];
}
getVariables() {
return {
name: this.props.node.name,
id: this.props.node.id,
userId: this.props.node.userId,
widgets: this.props.node.widgets
};
}
getOptimisticResponse() {
return {
formEdge: {
name: this.props.node.name,
id: this.props.node.id,
userId: this.props.node.userId,
widgets: this.props.node.widgets
}
};
}
}
And error message from browser:
"Variable "$input_0" got invalid value
{"name":"asdfasdfsa","id":"57e790cec252f32aa805e38d","userId":"57e10a02da7e1116c0906e40","widgets":[{"dataID":"client:618507132","label":"sdfas","type":"text","list":[],"description":"","required":true},{"label":"sfasdfasaaa","list":[],"type":"number","description":"","required":"false"}],"clientMutationId":"0"}.↵In
field "widgets": In element #0: In field "dataID": Unknown field."

Categories