Query a specific GET field? - javascript

How can I get just a single field (called "name") from an entry in my AppSync/Dynamo table, for a given "id:"? This is instead of getting the entire row of fields for that 'id' returned to me. I only need the single field.
The following doesn't work:
const userName = await API.graphql(graphqlOperation(GetUsers, { id: "3b342de-34k5-434....." }, "name") );
Schema:
type Users #model {
id: ID!
name: String
email: String
}
Query:
export const getUsers = `query GetUsers($id: ID!) {
getUsers(id: $id) {
id
name
email
}
}

Try below
export const getUser = `query GetUsers($id: ID!) {
getUsers(id: $id) {name}
}`
const userName = (await API.graphql(graphqlOperation(getUsers, {id: "xxx"}))).getUser.data.name
Be aware that the await gives you a nested object that includes the name. You have to extract it out. Besides, what you really need is type User, not type Users.

Your query is querying getUsers from your graphql server, and is asking for id, name, and email.
If you only want the name, change the query to this:
query GetUsers($id: ID!) {
getUsers(id: $id) {
name
}
}

Related

I am trying from two already created collections to add a field that has old_user, which is acUser, to user, but I don't know why it returns null

acUser is the field with existing data that I want to add to the collection
db.getCollection("old_user").find({id: 58})
.forEach((elm) => {
const userId = elm.id;
let userN = db.getCollection("user_new").find({ id: userId }).toArray()
if (userN) {
db.getCollection("old_user").updateOne({id: userId }, {$set: {newField: userN.acUser }});
}
})

Pass keys from type to object in Typescript

This is probably a very trivial question, but after reading other answers on typescript, my head is exploding.
Lets say I have a type of User fields I want to get
export type UserFileds = {
id: User["id"];
email: User["email"];
emailVerified: User["emailVerified"];
image: User["image"];
name: User["name"];
};
Now I need to get all of those fileds from the data I get. This is how I make it before:
const { id, email, emailVerified, image, name } = user as User;
return { id, email, emailVerified, image, name };
How can I put dynamically all this keys from UserFileds, like:
const { "list of keys of UserFileds" } = user as User;
Thanks

How do you set multiple properties to be returned in Javascript-React?

I am trying to build a search box. When you type in it, it automatically filters my App.js file (Cards of robots).
render() {
const filteredRobots = this.state.robots.filter(robots => {
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
return(
<div className='tc'>
<h1>RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange}/>
<CardList robots={filteredRobots}/>
</div>
)
}
I have a separate, robots.js file in which I list the properties of the robots:
export const robots = [
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere#april.biz'
},
My filter method works, when I only put a single property in it. In the code above, I am illustrating it when it is filtered by name. I would like to include the "email" property as well, so that when I type in the search field, it also filters by the email and not just the name.
Thanks in advance, this is my first post, sorry for not being clear, I recently started learning.
You can combine the objects fields into a single string and use it instead of using the name
const filteredRobots = this.state.robots.filter(robot => {
return Object.values(robot).join(" ").toLowerCase().includes(this.state.searchfield.toLowerCase())
})
Now, all the robot fields (name, username, email, id) are considered in your search function.
filter method passes the array items directly.
const searchedString = this.state.searchfield.toLowerCase()
const filteredRobots = robots.filter(robotItem => robotItem.name.toLowerCase().includes(searchedString) || robotItem.username.toLowerCase().includes(searchedString) )
more about the filter method in mdn docs

Can GraphQL optionally resolve a field given result of a query in resolver?

I have the following REST endpoints:
/orders/{id}
returns {
orderId,
orderItem,
customerId
}
/customers/{id}
returns {
customerId,
firstName,
lastName
}
I am limited by these two endpoints, which are going to be wrapped in my graphql schema.
I would like the following Schema:
type Order {
orderId: ID!,
orderItem: String,
customer: Customer
}
type Customer{
customerId: ID!
firstName: String!
lastName: String!
}
type Query {
getOrder(id: String!): Order,
getCustomer(id: String!): Customer
}
I'm wondering if it is possible to have GraphQL resolve the Customer object in the Order type? I understand that you cannot pass the result of a query into the parameter of another.
I have considered the resolver of getOrder be:
const getOrderResolver = axios.get(`/orders/${id}`)
.then((ordersRes) => {
let customerId;
if(ordersRes.data.customerId !== null) {
customerId = ordersRes.data.customerId
axios.get(`/customers/${customerId}`)
.then((customerRes) => ({
return {
orderId: ordersRes.data.orderId
orderItem: ordersRes.data.orderItem
customer: {
customerId: customerRes.data.customerId
firstName: customerRes.data.firstName
lastName: customerRes.data.lastName
}
}
})
} else {
return {
orderId: ordersRes.data.orderId
orderItem: ordersRes.data.orderItem
customer: null
}
}
})
})
getCustomer resolver
const getCustomerResolver = axios.get(`/customers/${customerId}`)
.then((customerRes) => ({
return {
customerId: customerRes.data.customerId
firstName: customerRes.data.firstName
lastName: customerRes.data.lastName
}
})
It seems with my solution, there will be the additional cost of always fetching the Customer type whether or not it is queried within the getOrder query. Is it possible to rewrite my GraphQL schema in a way that GraphQL would be able to resolve the Customer type only when queried?
The limitation of my given my ORDERS REST API only returns the CustomerId makes it difficult to resolve in getOrder, since the Customer API requires a customerId
There's two things to keep in mind here:
GraphQL won't resolve a field unless it's requested (i.e. your resolver will not be called unless the field is actually included in the request).
Each resolver has access to the value its "parent" field resolved to.
So your getOrder resolver can only worry about returning an order object:
const resolvers = {
Query: {
getOrder: (parent, args, context, info) => {
const response = await axios.get(`/orders/${args.id}`)
return response.data
},
...
},
...
}
Note that if the REST endpoint returns a response in the same "shape" as your field's type, there's no need to map the response data to your actual fields here -- just return response.data.
Now we can add a resolver for the customer field on our Order type:
const resolvers = {
Query: { ... },
Order: {
customer: (parent, args, context, info) => {
if (!parent.customerId) {
return null
}
const response = await axios.get('/customers/${parent.customerId}')
return response.data
},
},
...
}
Our parent field here will be getOrder (or any other field that has an Order type). The value of parent will be whatever value you returned in that field's resolver (or if you returned a Promise, whatever that Promise resolved to). So we can use parent.customerId for the call to the /customers endpoint and return the data from the response. And again, this resolver will only be called if the customer field is actually requested.

How to extract an object from an array?

I have this code, where a username is required from a fake db:
const MY_FAKE_DB = require('./my_db.js')
const username = 'jdoe2';
const user = MY_FAKE_DB.users[username];
console.log(user.name, user.passwordHash)
And the "dataBase" (my_db.js) is the next one:
const users =
{
jdoe2: [{
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
}],
lmart: [{
username: "lmart",
name: "Luis",
passwordHash: "2345"
}]
}
I donĀ“t know how to get from users the user whose username is jdoe2.
Thanks for the help
You have a few things that are causing problems here.
First to use require, you should export your object from the fake db. Something like:
// my_db.js
const users = {
jdoe2: {
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
},
lmart: {
username: "lmart",
name: "Luis",
passwordHash: "2345"
}
}
module.exports = users // export users
Notice I changed the DB. You defined each user as an array, but that doesn' make sense and you weren't accessing them as arrays. Here each user is a single object.
Now to use it you can require it and it should work as expected:
const users = require('./my_db.js') // the exported users becomes the `users`
const username = 'jdoe2';
const user = users[username];
console.log(user.name, user.passwordHash)

Categories

Resources