Realm TypeError: item.toJSON is not a function - react-native

I have the following error
TypeError: item.toJSON is not a function. (In 'item.toJSON(index.toString(), cache)', 'item.toJSON' is undefined)
The schemes are as follows:
export class MaturationCode {
public static schema: ObjectSchema = {
name: 'MaturationCode',
primaryKey: '_id',
properties: {
_id: { type: 'string' },
code: { type: 'string' },
},
};
}
export class Maturation {
public static schema: ObjectSchema = {
name: 'Maturation',
primaryKey: '_id',
properties: {
_id: { type: 'string' },
name: { type: 'string' },
codes: { type: 'list', objectType: 'MaturationCode', default: [] },
},
};
}
To read the registers I do the following:
public openRealm() {
return new Realm({
path: 'larvia.realm',
schema: ['MaturationCode', 'Maturation'],
schemaVersion: schemaVersion,
});
}
const data = realm.objects('Maturation');
The statement realm.objects('Maturation') throws the error.
I'm using:
"react-native": "0.66.3",
"realm": "^10.24.0"
And I don't use react-native-reanimated.

Related

Can't be blank - Password - Loopback 4 - JWT authentication

When I want to signup on the loopback API Explorer with a JWT authentication and this json format:
{
"id": "string",
"nom": "string",
"prenom": "string",
"email": "string",
"sexe": true,
"dateNaissance": "string",
"password": "strifsvng"
}
I had that error message :
{
"error": {
"statusCode": 422,
"name": "ValidationError",
"message": "L'instance `User` n'est pas valide. Détails : `password` can't be blank (value: undefined).",
"details": {
"context": "User",
"codes": {
"password": [
"presence"
]
},
"messages": {
"password": [
"can't be blank"
]
}
}
}
}
Here the link of the documentation's loopback I've used.
You can see here the user modal :
import {Entity, model, property} from '#loopback/repository';
#model()
export class User extends Entity {
#property({
type: 'number',
id: true,
generated: true,
})
id?: number;
#property({
type: 'string',
required: true,
})
nom: string;
#property({
type: 'string',
required: true,
})
prenom: string;
#property({
type: 'string',
required: true,
})
dateNaissance: string;
#property({
type: 'string',
required: true,
})
sexe: string;
#property({
type: 'string',
required: true,
})
email: string;
#property({
type: 'string',
required: true,
})
password: string;
constructor(data?: Partial<User>) {
super(data);
}
}
export interface UserRelations {
// describe navigational properties here
}
export type UserWithRelations = User & UserRelations;
and the user controller :
// import {inject} from '#loopback/core';
import {inject} from '#loopback/core';
import {
Credentials,
MyUserService,
TokenServiceBindings,
User,
UserRepository,
UserServiceBindings,
} from '#loopback/authentication-jwt';
import {authenticate, TokenService} from '#loopback/authentication';
import {model, property, repository} from '#loopback/repository';
import {get, getModelSchemaRef, post, requestBody} from '#loopback/rest';
import {SecurityBindings, securityId, UserProfile} from '#loopback/security';
import {genSalt, hash} from 'bcryptjs';
import _ from 'lodash';
#model()
export class NewUserRequest extends User {
#property({
type: 'string',
required: true,
})
password: string;
}
const CredentialsSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
email: {
type: 'string',
format: 'email',
},
password: {
type: 'string',
minLength: 8,
},
},
};
export const CredentialsRequestBody = {
description: 'The input of login function',
required: true,
content: {
'application/json': {schema: CredentialsSchema},
},
};
export class UserController {
constructor(
#inject(TokenServiceBindings.TOKEN_SERVICE)
public jwtService: TokenService,
#inject(UserServiceBindings.USER_SERVICE)
public userService: MyUserService,
#inject(SecurityBindings.USER, {optional: true})
public user: UserProfile,
#repository(UserRepository) protected userRepository: UserRepository,
) {}
#post('/users/login', {
responses: {
'200': {
description: 'Token',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
token: {
type: 'string',
},
},
},
},
},
},
},
})
async login(
#requestBody(CredentialsRequestBody) credentials: Credentials,
): Promise<{token: string}> {
// ensure the user exists, and the password is correct
const user = await this.userService.verifyCredentials(credentials);
// convert a User object into a UserProfile object (reduced set of properties)
const userProfile = this.userService.convertToUserProfile(user);
// create a JSON Web Token based on the user profile
const token = await this.jwtService.generateToken(userProfile);
return {token};
}
#authenticate('jwt')
#get('/whoAmI', {
responses: {
'200': {
description: '',
schema: {
type: 'string',
},
},
},
})
async whoAmI(
#inject(SecurityBindings.USER)
currentUserProfile: UserProfile,
): Promise<string> {
return currentUserProfile[securityId];
}
#post('/signup', {
responses: {
'200': {
description: 'User',
content: {
'application/json': {
schema: {
'x-ts-type': User,
},
},
},
},
},
})
async signUp(
#requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(NewUserRequest, {
title: 'NewUser',
}),
},
},
})
newUserRequest: NewUserRequest,
): Promise<User> {
const password = await hash(newUserRequest.password, await genSalt());
const savedUser = await this.userRepository.create(
_.omit(newUserRequest, 'password'),
);
await this.userRepository.userCredentials(savedUser.id).create({password});
return savedUser;
}
}
I don't know why there are that error as I write something in the password.
Thank you in advance :)

JSON-SCHEMA arbitrary names on top level

I'm using json-schema with a nodeJs backend called 'feathers-plus' which validate data using popular ajv.
I've got two objects -> ObjectA & ObjectB where ObjectA is the parent.
ObjectA contain a collection of ObjectB that have arbitrary names defined by patternProperties and which is objects:
exchanges: {
type: 'object',
patternProperties: {
"^[A-Za-z]+$": {
type: 'object'
}
},
additionalProperties: false
},
ObjectB (which is an exchange in my case) start with this arbitrary key name on top-level and then contain itself more properties (on second level and so on).
The problem is I don't know how to define these arbitrary keys names. I know how to define it on second level and more deeply using the example above for exchanges. But on top, I suppose I can't write something like this:
"^[A-Za-z]+$": {
type: 'object'
}
With feathers-plus, we can separate our logical objects in services. In my case here, the top service is called "configs" and the child one "exchanges".
Any help would be grateful.
Thanks!
EDIT: as requested, I post my current schemas for both objects:
Parent ObjectA ->
let schema = {
title: 'Configs',
description: 'Configs database.',
required: [
'name',
'bot',
'GUI',
'ws',
'createdAt',
'updatedAt'
],
uniqueItemProperties: [
],
properties: {
id: { type: 'ID' },
name: {},
pairs: {
type: 'object',
patternProperties: {
"^[A-Za-z]+$": {
type: 'object'
}
},
additionalProperties: false
},
// THIS IS THE CONTAINER FOR EXCHANGES OBJECTS
exchanges: {
type: 'object',
patternProperties: {
"^[A-Za-z]+$": {
type: 'object'
}
},
additionalProperties: false
},
// END
bot: {
type: 'object',
properties: {
debug: { type: 'boolean' },
gui: { type: 'boolean' },
period_storage_ticker: { type: 'number' },
interval_ticker_update: { type: 'number' },
timeout_buy: { type: 'number' },
timeout_sell: { type: 'number' },
WATCH_MODE: { type: 'boolean' },
TELEGRAM_ENABLED: { type: 'boolean' },
TELEGRAM_NICK: {},
TOKEN: {},
chat_id: { type: 'number' }
},
required: [
'debug',
'gui',
'period_storage_ticker',
'interval_ticker_update',
'timeout_buy',
'timeout_sell',
'WATCH_MODE',
'TELEGRAM_ENABLED',
'TELEGRAM_NICK',
'TOKEN',
'chat_id'
]
},
GUI: {
type: 'object',
properties: {
enabled: { type: 'boolean' },
start: { type: 'boolean' },
port: { type: 'number' },
https: { type: 'boolean' },
key: {},
cert: {},
networktraffic: { type: 'boolean' },
authentication: {
type: 'object',
properties: {
login: { type: 'boolean' },
twoFA: { type: 'boolean' }
},
required: [
'login',
'twoFA'
]
},
notifications: {
type: 'object',
properties: {
trade: { type: 'boolean' },
callback: { type: 'boolean' },
error: { type: 'boolean' }
},
required: [
'trade',
'callback',
'error'
]
}
},
required: [
'enabled',
'start',
'port',
'https',
'key',
'cert',
'networktraffic',
'authentication',
'notifications'
]
},
ws: {
type: 'object',
properties: {
port: { type: 'number' },
clientport: { type: 'number' },
hostname: {}
},
required: [
'port',
'clientport',
'hostname'
]
}
createdAt: {},
updatedAt: {}
}
}
Child ObjectB ->
let schema = {
title: 'Exchanges',
description: 'Exchanges database.',
// MY CURRENT EDIT (NOT WORKING)
type: 'object',
patternProperties: {
"^[A-Za-z]+$": { type: 'boolean' }
},
additionalProperties: false,
// END
required: [
],
uniqueItemProperties: [
],
properties: {
},
}
If I'm making a request and try to pass anything, it works and validation is not made. The same patternProperties set on a deeper level have no problem at all and is validated correctly.

Apollo-Client | No result from query when using certain fields

I'm trying to use apollo-client in my react-native app but for some reason I can only get results from queries when I use certain fields.
Here's my first query :
`query RootQueryType($page: Int!) {
events(page: $page) {
title
}
}`
Working perfectly in RN and GraphiQL but as soon as I add or use an other field than title I don't get any result from the query in RN. It's working perfectly in GraphiQL and there's no error at all.
For example :
`query RootQueryType($page: Int!) {
events(page: $page) {
description
}
}`
Here's my event type :
const EventType = new GraphQLObjectType({
name: 'EventType',
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
category: { type: GraphQLString },
description: { type: GraphQLString },
terminated: { type: GraphQLBoolean },
coverUrl: { type: GraphQLString },
startDate: { type: GraphQLString },
endDate: { type: GraphQLString },
price: { type: GraphQLFloat },
website: { type: GraphQLString },
ticketsUrl: { type: GraphQLString },
geometry: { type: GraphQLString },
participantsCount: { type: GraphQLInt },
participants: {
type: new GraphQLList(UserType),
resolve(parentValue) {
return Event.findParticipants(parentValue.id);
}
}
})
});

Transpiled GraphQL with Babel is throwing error "Cannot call class as function"

I am trying to get running GraphQL server. I have simple schema in GraphQL
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLSchema
} from 'graphql'
import db from './models'
const user = new GraphQLObjectType({
name: "user",
description: 'This represents a user',
fields: () => {
return {
id: {
type: GraphQLInt,
resolve(user) {
return user.id
}
},
firstName: {
type: GraphQLString,
resole(user) {
return user.firstName
}
},
lastName: {
type: GraphQLString,
resole(user) {
return user.lastName
}
},
email: {
type: GraphQLString,
resole(user) {
return user.email
}
},
createdAt: {
type: GraphQLString,
resole(user) {
return user.createdAt
}
},
updatedAt: {
type: GraphQLString,
resole(user) => {
return user.updatedAt
}
}
}
}
})
const Query = new GraphQLObjectType({
name: 'Query',
description: 'This is root Query',
fields: () => {
return {
users: {
type: GraphQLList(user),
args: {
id: {
type: GraphQLInt
},
email: {
type: GraphQLString
}
},
resolve(root, args) {
return db.user.findAll({where: args})
}
}
}
}
})
const Schema = new GraphQLSchema({
query: Query
})
export default Schema
I am transpile it with babel into ES5, but every time when I try run it with express
import GraphHTTP from 'express-graphql'
import Schema from './schema'
app.use('/grapql', GraphHTTP({
schema: Schema,
pretty: true,
graphiql: true
}))
I am getting this error
\node_modules\graphql\type\definition.js:41
function _classCallCheck(instance, Constructor) { if (!instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }                                                             
TypeError: Cannot call a class as a function
I check it again and again if i have some typing error but i didnt find enything.
instead of type: GraphQLList(user) use type: new GraphQLList(user)
GraphQLList is a class and you have to create it's instance and use, but you have called it as a function.
const Query = new GraphQLObjectType({
name: 'Query',
description: 'This is root Query',
fields: () => {
return {
users: {
type: new GraphQLList(user),
args: {
id: {
type: GraphQLInt
},
email: {
type: GraphQLString
}
},
resolve(root, args) {
return db.user.findAll({where: args})
}
}
}
}
})

Sencha localStorage.getItem() returns null in model

In my model, I have the following code:
Ext.define('Proximity.model.CandidateblocklistModel', {
extend: 'Ext.data.Model',
requires: ['Ext.data.proxy.LocalStorage'],
config: {
store:'Proximity.store.CandidateblockStore',
fields: [
{ name: 'id', type: 'id' },
{ name: 'name', type: 'string' },
{ name: 'img', type: 'string' },
{ name: 'designation', type: 'string' },
{ name: 'summary', type: 'string' },
{ name: 'experience', type: 'string' },
{ name: 'industry', type: 'string' },
{ name: 'functionnml', type: 'string' },
{ name: 'role', type: 'string' }
],
proxy : {
type : 'ajax',
url : Proximity.util.Config.getBaseUrl() + '/index.php/candidate/getcandidateblock',
withCredentials: false,
useDefaultXhrHeader: false,
extraParams: {
"id": localStorage.getItem('id')
},
reader : {
filters: [
Ext.create('Ext.util.Filter', {
property: 'name'
})
]
}
}
}
});
The id in the local storage is already set before calling this model. I can see the id in localStorage by inspect element in Chrome, and I did get the value of it in other section. But I only can't get it in my model when I am trying to use it in proxy. I want to get data from my web service based on the value of the localStorage.
Code in my proxy:
extraParams: {
"id": localStorage.getItem('id')
},
I want to get the id from localStorage here.
Please help me.
I think the following code works
proxy : {
type : 'ajax',
url : Proximity.util.Config.getBaseUrl() + '/index.php/candidate/getcandidatebest',
withCredentials: false,
useDefaultXhrHeader: false,
extraParams: {
id: localStorage.getItem('id')
},
reader : {
filters: [
Ext.create('Ext.util.Filter', {
property: 'ind_id',
property: 'fun_id',
property: 'role_id',
property: 'id'
})
]
}
}
and then use the filtering facility of store to pass the localstorage value. To do that give filter permission remoteFilter: true, this.
Ahh i found an awesome trick. Instate of setting extraParams in your Model, set it in the store of the same model.
My new code is as follows.
Ext.define('Proximity.model.RecruiterbestlistModel', {
extend: 'Ext.data.Model',
config: {
store:'Proximity.store.RecruiterbestStore',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string' },
{ name: 'img', type: 'string' },
{ name: 'company', type: 'string' },
{ name: 'summary', type: 'string' },
{ name: 'address', type: 'string' },
{ name: 'industry', type: 'string' },
{ name: 'functionnml', type: 'string' },
{ name: 'role', type: 'string' }
],
proxy : {
type : 'ajax',
url : Proximity.util.Config.getBaseUrl() + '/index.php/recruiter/getrecruiterbest/',
withCredentials: false,
useDefaultXhrHeader: false,
reader : {
filters: [
Ext.create('Ext.util.Filter', {
property: 'ind_id',
property: 'fun_id',
property: 'role_id'
})
]
}
}
}
});
Look i have removed the code
extraParams: {
"id": localStorage.getItem('id')
},
from Model. And in my store i have added
listeners: {
beforeload: function(store){
this.getProxy().setExtraParams({
id: localStorage.getItem('id')
});
return true;
},
So my new store code is as follows
Ext.define('Proximity.store.RecruiterbestStore', {
extend: 'Ext.data.Store',
alias: 'store.recruiterbeststore',
config: {
model: 'Proximity.model.RecruiterbestlistModel',
autoLoad: true,
remoteFilter: true,
storeId: 'recruiterbeststore'
},
listeners: {
beforeload: function(store){
this.getProxy().setExtraParams({
id: localStorage.getItem('id')
});
return true;
}
}
});
And its solved my problem.
But now i am having another issue. after running sencha app build native(using cordova bild), again i am having same issue, the extraParam are not added to proxy request.
Please help me to solve this.