Viewing object returned from realm.object() - react-native

I added data to a realm using
realm.write(() => {
for (const player in players) {
realm.create('Player', {
id: player.id,
firstname: player.firstname,
lastname: player.lastname,
});
}
});
players is a JSON array.
[
{
"id": 9687,
"firstname": "Nyeem",
"lastname": "Young",
},
{
"id": 100,
"firstname": "Jason",
"lastname": "Holder",
}]
I was able to confirm that the data was entered successfully by using
realmPlayers = realm.objects('Player');
console.log(`There are ${realmPlayers.length} players`); // 99
However when I try to get all the players
console.log(realmPlayers)
I get the error
[TypeError: item.toJSON is not a f
unction. (In 'item.toJSON(index.toString(), cache)', 'item.toJSON' is undefined)]
console.log(JSON.stringify(realmPlayers)); gives the same error.
console.log(realmPlayers[0]); returns {}
Trying to use a filter
realm.objects('Player').filtered('lastname = Young');
I get the error
Failed to open the realm 'Player' has no property: 'Young'
If I have items in the database why can't I access it. Ultimately what I want to do is to get all the items in the database and pass the result to a FlatList component in React Native..
How can I get the data and possible visualize it via the command line?

Related

Flutter extracting data from a list inside a map from API call

I have a flutter http get request that returns a response in the below format
{
"area": "some area",
"user_places": [
{
"place_id": "105",
"place_name": "Place 1"
},
{
"place_id": "104",
"place_name": "place 2"
}
],
"lang": null,
"token": "IiwiZGV2aWNlIjoid2ViIiwiZGllIjoiMjAyMS0wNS0xMiAyMjo0NTozOSJ9.2wJlmHNRmQ0_rfNbca2-DNek1dzT9Em8-iQIfGFZJ98",
"account_type": 1,
}
Am currently able to get data from a field directly below the map for example "area" .
My question is how to get data from a list inside the map in this case "user_places". Say I wanted to display all "place_id" and "place_name" in a widget somewhere in my app. How would I go about it?
you can use a tool like json to dart you can paste your json data and get a dart class of the same
class MyLocation {
String area;
List<UserPlaces> userPlaces;
String lang;
String token;
int accountType;
MyLocation(
{this.area, this.userPlaces, this.lang, this.token, this.accountType});
....
then MyLocation.userPlaces you can access your data

Removing join table data in sequelize returned value

I am currently trying to remove a joint table data added when retrieving an association data.
The query is done by sequelize using a method added to the model through specifying model relationships(sequelize magic methods), for some reason, I'm not able to do that.
I have currently tried passing in attributes: {exclude: ['...']} to the method but the field still persists.
Current association
// Class sequelize model
Class.belongsToMany(models.Subject, {
through: 'ClassSubject',
foreignKey: 'class_id',
otherKey: 'subject_id',
as: 'subjects'
})
// Subject sequelize model
Subject.belongsToMany(models.Class, {
through: 'ClassSubject',
foreignKey: 'subject_id',
otherKey: 'class_id',
as: 'classes'
});
Query and Response
const subjects = await dbClass.getSubjects(); // dbClass is a Class model instance
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1",
"ClassSubject": {
"class_id": "637afc7b-40f6-478e-b35e-859ca462e2e7",
"subject_id": "1b89d44c-2caa-452d-a1f8-7faa11970917"
}
}
]
Desired output
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1"
}
]
I have tried passing options to the method as specified below but to no avail
const subjects = await dbClass.getSubjects({
attributes: { exclude: ['ClassSubject'] }
});
But it still doesn't work.
Try using the joinTableAttributes option and pass empty array to exclude everything in joint table.
const subjects = await dbClass.getSubjects({ joinTableAttributes: [] });

How to update the Strapi GraphQL cache, after creating new data?

How to update the cache, after creating new data?
Error message from Apollo
Store error: the application attempted to write an object with no provided id but the store already contains an id of UsersPermissionsUser:1 for this object. The selectionSet that was trying to be written is:
{
"kind": "Field",
"name": { "kind": "Name", "value": "user" },
"arguments": [],
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{ "kind": "Field", "name": { "kind": "Name", "value": "username" }, "arguments": [], "directives": [] },
{ "kind": "Field", "name": { "kind": "Name", "value": "__typename" } }
]
}
}
Nativescript-vue Front-end Details
1- Watch Book Mobile app in action on YouTube: https://youtu.be/sBM-ErjXWuw
2- Watch Question video for details on YouTube: https://youtu.be/wqvrcBRQpZg
{N}-vue AddBook.vue file
apolloClient
.mutate({
// Query
mutation: mutations.CREATE_BOOK,
// Parameters
variables: {
name: this.book.name,
year: this.book.year,
},
// HOW TO UPDATE
update: (store, { data }) => {
console.log("data ::::>> ", data.createBook.book);
const bookQuery = {
query: queries.ALL_BOOKS,
};
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
const bookData:any = store.readQuery(bookQuery);
console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
bookData.books.push(data.createBook.book);
store.writeQuery({ ...bookQuery, data: bookData })
},
})
.then((data) => {
// I can even see ID in Result
console.log("new data.data id ::::: :>> ", data.data.createBook.book.id);
this.$navigateTo(App);
})
.catch((error) => {
// Error
console.error(error);
});
What are these "Book:9": { lines in the cache?
console.log store turns out:
"Book:9": {
"id": "9",
"name": "Hadi",
"year": "255",
"__typename": "Book"
},
"$ROOT_MUTATION.createBook({\"input\":{\"data\":{\"name\":\"Hadi\",\"year\":\"255\"}}})": {
You can see all front-end GitHub repo here
Download Android apk file
Our goal is to update the cache. Add Book Method is in here:
https://github.com/kaanguru/mutate-question/blob/c199f8dcc8e80e83abdbcde4811770b766befcb5/nativescript-vue/app/components/AddBook.vue#L39
Back-end details
However, this is a frontend question a running Strapi GraphQL Server is here: https://polar-badlands-01357.herokuapp.com/admin/
GraphQL Playground
USER: admin
PASSWORD: passw123
You can see GraphQL documentation
I have so much simple Strapi GrapQL Scheme:
If you want to test it using postman or insomnia you can use;
POST GraphQL Query URL: https://polar-badlands-01357.herokuapp.com/graphql
Bearer Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTkwODI3MzE0LCJleHAiOjE1OTM0MTkzMTR9.WIK-f4dkwVAyIlP20v1PFoflpwGmRYgRrsQiRFgGdqg
NOTE: Don't get confused with $navigateTo() it's just a custom method of nativescript-vue.
It turns out;
all code was correct accept bookData.push(createBook);
// HOW TO UPDATE
update: (store, { data }) => {
console.log("data ::::>> ", data.createBook.book);
const bookQuery = {
query: queries.ALL_BOOKS,
};
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
const bookData:any = store.readQuery(bookQuery);
console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
bookData.books.push(data.createBook.book);
store.writeQuery({ ...bookQuery, data: bookData })
},
})
Typescipt was helping
The point is; I shouldn't trust TypeScript errors, or at least I should read more about what it really says.
Typescript just asked me to be more specific while saying: Property 'push' does not exist on type 'unknown'
TypeScript was trying to tell me I need to be more specific while calling ROOT_MUTATION data. It said: Cannot find name 'createBook' But again I ignored it.
Solution Github Branch
https://github.com/kaanguru/mutate-question/tree/solution
Sources
how to update cache
Create interface for object Typescript

graphql error: mutation with where not working

I am using Prisma GraphqQL and I got this error for a mutation with where selector:
"You provided an invalid argument for the where selector on User"
Mutation:
mutation UpdateUserMutation($data: UserUpdateInput!, $where: UserWhereUniqueInput!) {
updateUser(data: $data, where: $where) {
id
name
email
role
}
}
Variables:
{
"data": {
"name": "alan", "email": "alan#gmail.com", "role": "ADMIN"
},
"where": {
"id": "cjfsvcaaf00an08162sacx43i"
}
}
Result:
{
"data": {
"updateUser": null
},
"errors": [
{
"message": "You provided an invalid argument for the where selector on User.",
"locations": [],
"path": [
"updateUser"
],
"code": 3040,
"requestId": "api:api:cjftyj8ov00gi0816o4vvgpm5"
}
]
}
Schema:
updateUser(
data: UserUpdateInput!
where: UserWhereUniqueInput!
): User
type UserWhereUniqueInput {
id: ID
resetPasswordToken: String
email: String
}
Why this mutation is not working?
With colors:
Mutation GraphQL
Schema Graphql
EXTRA INFORMATION
Full code of this Project is here:
Graphql playground is here:
Console view (variable are empty):
Query for user (with id: cjfsvcaaf00an08162sacx43i). So user can be found with "where" operator in query, but not in mutation.
Your updateUser resolver is not implemented correctly:
async function updateUser(parent, { id, name, email, role }, ctx, info) {
// console.log( id, name, email)
await ctx.db.mutation.updateUser({
where: { id: id },
data: {name: name, email: email, role: role},
})
}
Your mutation has the two parameters data and where, but you expect the parameter list { id, name, email, role }.
Either update your schema, or your resolver accordingly.
Source: https://github.com/graphcool/prisma/issues/2211

Facebook API (javascript) getting latest school education info

I'm very new to the facebook api for my website, and I am using the javascript sdk. I want to get the users latest school information, including school name, course and year of study. This is what I have so far but it breaks the login script and returns 'response.education.school is undefined'. I'm guessing I'll need some kind of for loop to go through the education array as most users have more than one school listed?
function login() {
FB.login(function(response) {
if(response.authResponse) {
// connected
FB.api('/me', function(response) {
fbLogin(response.id, response.name, response.firstname, response.email,
response.education.school.name, response.education.concentration.name, response.education.year.name);
});
} else {
// cancelled
}
}, {scope: 'email, user_education_history, user_hometown'});
}
response.education.school is undefined
This is because responce.education is an array of objects. This would be an example for me (actual information removed)
"education": [
{
"school": {
"id": "",
"name": ""
},
"year": {
"id": "",
"name": ""
},
"concentration": [
{
"id": "",
"name": ""
}
],
"type": ""
},
...
]
You need to iterate over it and process each educaional step e.g.
for(ed in response.education) {
var school = response.education[ed].school;
var schoolName = school.name;
...
}
And so on; you are currently passing an aobject structure to your fbLogIn that can't handle it. If you want the latest school education, you simply pick the one that has the most recent year.name value.