I am trying to filter the data coming back from FindAll cause I only want data from a certain provider
// Data coming back from API
{
"-KDinaItb7lkHpai-DlG": {
"email": "johns#test.com",
"name": "John Smith",
"notes": "John is a great employee and is the best",
"phone": "215-543-9830",
"provider": "-KDhzbilOvv7Evuc5S_X"
},
"-KDjS0cCxFWQctcwXg0V": {
"email": "amanda#test.com",
"name": "Amanda Harrington",
"notes": "Amanda is a great employee",
"phone": "215-543-9830",
"provider": "-KDiokWebdhTNKTORWwn"
},
"-KDyf7pU_PyxRQSgFB59": {
"email": "lguy#test.com",
"name": "Larry Guy",
"notes": "He is a funny guy",
"phone": "702-454-2397",
"provider": "-KDhzbilOvv7Evuc5S_X"
}
}
// In the route
let providerId = model.get('provider').get('id');
this.store.findAll('employee').then(function(results) {
let prov = results.filterBy('provider', providerId);
console.log(prov);
});
When the console log happens and it returns an empty array. I think its because of the ID and its not looking at the nested object. Anyone got any thoughts?
Ok so your hash looks quite odd. Property name shouldn't be some generated hash.
code should be something like that.
I assume you have 1 wrapper object on index 0 within an array.
var filteredEmployees_promise = this.store.findAll('employee').then(function(results) {
var filteredResults = [];
Object.keys(Results[0]).forEach(key => {
var filteredObj = Results[0][key][providerId];
if(Ember.isPresent(filteredObj) {
filteredResults.pushObject(filteredObj)
}
});
return filteredResults;
});
And later
filterEmployees_promise.then(employees => { // Custom stuff })
Related
Data:
[
{
"name": "Gates of Olympus",
"slug": {
"_type": "slug",
"current": "gates-of-olympus"
}
},
{
"name": "Floating Dragon",
"slug": {
"_type": "slug",
"current": "floating-dragon"
}
},
{
"name": "Buffalo King Megaways",
"slug": {
"_type": "slug",
"current": "buffalo-king-megaways"
}
},
{
"name": "Fruit Party",
"slug": {
"_type": "slug",
"current": "fruit-party"
}
}
]
How do I query only objects with slug gates-of-olympus ?
Code:
export const getServerSideProps = async ({params}:any) => {
const query = `*[_type=="game"]{
name,
slug,
}`;
const games = await sanityClient.fetch(query);
return {
props: {
games,
},
};
};
slug is obtained through context (params.game).
I also tried,
*[_type=="game" && slug.current == ${params.game}] but still returns all data.
Wrap ${params.game} with the quotes. Like this "${params.game}". It will work
You get back all the data but the first one or first item in that array of data is the one your searching for so at the end of your query put [0] at the end to get the first value you should be solid eg *[_type=="game" && slug.current == '${params.game}'][0]
Ref
go to this video which is taught by js mastery skip to 1:21:27 he starts explaining how to get the current slug/product https://www.youtube.com/watch?v=4mOkFXyxfsU&t=5153s
I have a data structure in firebase
{
"name": "Sample",
"category": ["123456", "789012"]
}
The array of category contains ID which refers to documents in another collection. I can get the above document as Observable. What I really what as the end result is the below data structure
{
"name": "Sample"
"category": [
{
"name": "Category 1"
},
{
"name": "Category 2"
}
]
}
How can I bring this data? I don't think switchMap works for this. If so, can someone give an example of that?
You can try using flatMap and forkJoin. FlatMap allows you to chain multiple async requests together and forkJoin allows you to wait for all observables to return a value before continuing.
And you could wright something like this:
var finalData;
firstRequest('sample').flatMap((data) => {
// assuming data = { name: "Sample", catagory: [ "23123", "31321", ... ] }
finalData = data;
var observables = [];
data.catagory.forEach((c) => {
observable.push(secondRequest(c));
});
return forkJoin(observables);
}).flatMap((results) => {
// assuming results is an array like [ { name: "Catagory 1", ... } ]
finalData.category = results;
return finalData;
});
I am trying to put a hard-coded data item to DynamoDB. I am using AWS SDK object to perform this update. And all the debug "Console.log" in the below code is getting printed but eventually it prints Task timed out after 3.00 seconds
With no update to the DynamoDB
function updatedb(intent, session, callback) {
let country;
const repromptText = null;
const sessionAttributes = {};
let shouldEndSession = false;
console.log("In the function");
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });
var params = {
TableName: "Location",
Item: {
"LocationID": { "S": "11" },
"Country": { "S": "10" },
"Description": { "S": "10" },
"Name": { "S": "10" }
}
};
console.log("Param loaded & executing the DocClient Put");
docClient.put(params, function (err, data) {
if (err) {
speechOutput = 'Update failed';
console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
} else {
console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
speechOutput = 'Update successful';
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
}
});
}
The following items are already checked
1) There is a table named "Location" in DynamoDB
2) Both DynamoDB and this lambda function are in ue-west-1 (Ireland)
3) The role assigned for this Lambda function can do all operation on this table. See the policy details below
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1510603004000",
"Effect": "Allow",
"Action": [
"dynamodb:*"
],
"Resource": [
"arn:aws:dynamodb:eu-west-1:752546663632:table/Location"
]
}
]
}
How does my Lambda function locate the table "location" just with the region?- the code does not appear to have end-point, etc.? - just developed based on a tutorial.
Is that what I am missing?
Please can you help?
I had a similar issue, try putting require statements in the beginning of your function.
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' });
I believe that AWS locates the table based on your identity, in combination with the region and the table name.
I was able to successfully post to a table using this code:
const AWS = require('aws-sdk');
const dynamoDB = new AWS.DynamoDB({region: 'us-west-2'});
var params = {
TableName: "my-table",
Item: {
"LocationID": { S: "11" },
"Country": { S: "10" },
"Description": { S: "10" },
"Name": { S: "10" }
}
};
dynamoDB.putItem(params, (err, data) => {
if (err){
console.error(err.stack);
} else {
console.log(data);
}
});
If you can in fact post to the table from the CLI, then there is still at least one remaining issue: it appears that you are using the DocumentClient class incorrectly. It looks like you're mixing up the syntax for DynamoDB.putItem with the syntax for DynamoDB.DocumentClient.put.
If you notice, my code uses the DynamoDB class directly-- based on what you're doing, I see no reason why you couldn't do the same. Otherwise, you should change your Item object:
var params = {
TableName: "my-table",
Item: {
"LocationID": "11",
"Country": "10",
"Description": "10",
"Name": "10"
}
};
My guess is your code is currently erroring out because you are trying to insert Maps where you want to insert Strings. If you have Cloudwatch configured you could check the logs.
Finally, I don't see you using callback in your code. If your intention is to respond to a client calling the lambda you should do that. Depending on your NodeJS version, the lambda can simply time out without returning a useful response.
I'm new to redux and it's hard to grasp how to implement good state shape without duplicating data, in case I need to update it, and naive way would be to update in few places, but that would negate the single source of truth.
We fetch user profile and posts from API server:
www.api.com/users/placeholder
{
"user": {
"username": "placeholder",
"bio": "It's my bio",
"profileImage": "http://via.placeholder.com/350x150",
"isViewerFollowing": false
}
}
www.api.com/posts?author=placeholder
{
"posts":[{
"id": "1",
"caption":"caption placeholder",
"image":"http://via.placeholder.com/1000x1000",
"createdAt": "2017-08-18T03:22:56.637Z",
"updatedAt": "2016-08-18T03:48:35.824Z",
"isLikedbyViewer": false,
"likesCount": 0,
"author": {
"username": "placeholder",
"bio": "It's my bio",
"profileImage": "http://via.placeholder.com/350x150",
"isViewerFollowing": false,
}
},
{
"id": "2",
"caption":"caption placeholder",
"image":"http://via.placeholder.com/1000x1000",
"createdAt": "2017-08-18T03:22:56.637Z",
"updatedAt": "2016-08-18T03:48:35.824Z",
"isViewerLiked": false,
"likesCount": 0,
"author": {
"username": "placeholder",
"bio": "It's my bio",
"profileImage": "http://via.placeholder.com/350x150",
"isViewerFollowing": false,
}
}],
"postsCount": 2
}
For example, we have separate reducers for users and posts, and user wants to follow user/author, then we would need to update information in two reducers. So my final question would be, could someone hint me what would good state shape look like in this particular example ?
Thanks!
You should normalize your Redux state: instead of saving the entire author object for every post, you should just save the authorId.
Since you ensure that when you have a post object in the posts branch of your Redux state, you also have the related author in the authors branch, to retrieve all the posts with their author's data you can create a selector:
export function getPosts(reduxState) {
return reduxState.posts.map(post => {
const author = reduxState.authors.find(a => a.id === post.authorId);
return {
...post,
author
};
});
}
Here's the scenario: I have a list of topics, each topic includes posts, and each post was "liked" by a list of users. Thus my data looks something like this:
"topics": {
"topic1": {
"posts": {
"post1": true,
"post2": true
}
}
},
"posts": {
"post1": {
"title": "An awesome post",
"likes": {
"user1": true
}
},
"post2": {
"title": "An even better post",
"likes": {
"user1": true,
"user2": true
}
}
},
"users": {
"user1": {
"name": "Mr. T",
"email": "t#t.com"
},
"user2": {
"name": "Mr. Hello World",
"email": "hello#world.com"
}
}
I (think I) know how to get all posts for the topic using Firebase.util (http://firebase.github.io/firebase-util):
Firebase.util.intersection(
fb.child('topics').child('topic1').child('posts'),
fb.child('posts')
)
But now I would like each post to include the names of the users who liked the post. How does one do that?
Probably won't change anything, but this is all happening in AngularFire.
See a working example here
The gist of this sort of denormalization is to fetch the users as you grab posts. It's nothing more complex than it sounds. Just go grab them.
Firebase does a lot of work internally to optimize requests and re-uses the same socket connection for all the listeners, so this is quite performant--barely more overhead than the amount of bytes being downloaded, regardless of whether they are split into separate paths or stored together.
The HTML:
<h3>Normalizing user profiles into posts</h3>
<ul ng-controller="ctrl">
<li ng-repeat="post in posts | orderByPriority" ng-init="user = users.$load(post.user)">
{{user.name}}: {{post.title}}
</li>
</ul>
The JavaScript:
var app = angular.module('app', ['firebase']);
var fb = new Firebase(URL);
app.controller('ctrl', function ($scope, $firebase, userCache) {
$scope.posts = $firebase(fb.child('posts'));
$scope.users = userCache(fb.child('users'));
});
app.factory('userCache', function ($firebase) {
return function (ref) {
var cachedUsers = {};
cachedUsers.$load = function (id) {
if( !cachedUsers.hasOwnProperty(id) ) {
cachedUsers[id] = $firebase(ref.child(id));
}
return cachedUsers[id];
};
cachedUsers.$dispose = function () {
angular.forEach(cachedUsers, function (user) {
user.$off();
});
};
return cachedUsers;
}
});