Realm sync not working for embedded objects in react native - react-native

This is my collection schema on realm -
{
"title": "testnote",
"properties": {
"_id": {
"bsonType": "objectId"
},
"_syncPartition": {
"bsonType": "string"
},
"title": {
"bsonType": "string"
},
"description": {
"bsonType": "string"
},
"subject": {
"bsonType": "string"
},
"tags": {
"bsonType": "array",
"items": {
"bsonType": "string"
}
},
"pages": {
"bsonType": "array",
"items": {
"title": "notespage",
"bsonType": "object",
"properties": {
"type": {
"bsonType": "string"
},
"data": {
"bsonType": "string"
}
}
}
},
"createdBy": {
"bsonType": "string"
}
}
}
This is how I've declared realm schema in react native. The code to initialize the Realm connection is also added below.
static NotesPage = {
name: "notespage",
embedded: true,
properties: {
type: "string",
data: "string"
}
}
static mainSchema = {
name: "testnote",
properties: {
_id: "objectId?",
_syncPartition: "string?",
createdBy: "string?",
title: "string?",
description: "string?",
subject: "string?",
tags: "string[]",
pages: { type: "list", objectType: "notespage" }
},
primaryKey: "_id"
};
const sampleNotesConfig = {
schema: [mainSchema NotesPage],
sync: {
user,
partitionValue: notesPartition,
newRealmFileBehavior: OpenRealmBehaviorConfiguration,
existingRealmFileBehavior: OpenRealmBehaviorConfiguration
}
};
Realm.open(sampleNotesConfig).then((notesRealm) => {
//// Some relevant code
}).catch((reason) => {
console.log("Error initializing realm");
console.log(reason);
});
When I create the realm object, it gets inserted in the local realm file but never gets synced to the server. I don't see any server errors or errors in local.
notesRealm.write(() => {
notesRealm.create(
SampleNote.schema.name,
{
"subject": "History",
"title": "Local to Remote Note 10",
"description": "Local to Remote Note 10 Description",
"tags": ["Tag 1", "Tag 2", "Tag 3"],
"pages": [{"type": "COVER_PAGE", "data": "Data 1"}, { "type": "PARAGRAPH", "data": "Data 2"}]
});
});
I have checked following things -
Partition values are correct.
User has permission to read/write to that partition.
If I just remove the pages section from the schema, the object starts syncing.

Related

React jsonschema form - schema does not exist on property type

I'm tryin to use react json schema form but having couple of issuea and can't work it out why! Any help would be awesome
import { useEffect, useState } from "react";
import Form from "#rjsf/core";
import { JSONSchema7 } from "json-schema";
import validator from "#rjsf/validator-ajv8";
const mopSchema:JSONSchema7 = {
"title": "A registration form",
"description": "A simple form example.",
"type": "object",
"required": [
"firstName",
"lastName"
],
"properties": {
"firstName": {
"type": "string",
"title": "First name",
"default": "Chuck"
},
"lastName": {
"type": "string",
"title": "Last name"
},
"age": {
"type": "integer",
"title": "Age"
},
"bio": {
"type": "string",
"title": "Bio"
},
"password": {
"type": "string",
"title": "Password",
"minLength": 3
},
"telephone": {
"type": "string",
"title": "Telephone",
"minLength": 10
}
}
};
const uiSchema = {
"firstName": {
"ui:autofocus": true,
"ui:emptyValue": "",
"ui:autocomplete": "family-name"
},
"lastName": {
"ui:emptyValue": "",
"ui:autocomplete": "given-name"
},
"age": {
"ui:widget": "updown",
"ui:title": "Age of person",
"ui:description": "(earth year)"
},
"bio": {
"ui:widget": "textarea"
},
"password": {
"ui:widget": "password",
"ui:help": "Hint: Make it strong!"
},
"telephone": {
"ui:options": {
"inputType": "tel"
}
}
};
The ts error:
Type '{ schema: any; uiSchema: { firstName: { "ui:autofocus": boolean; "ui:emptyValue": string; "ui:autocomplete": string; }; lastName: { "ui:emptyValue": string; "ui:autocomplete": string; }; age: { "ui:widget": string; "ui:title": string; "ui:description": string; }; bio: { ...; }; password: { ...; }; telephone: { ...; ...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Form<any, RJSFSchema, any>> & Readonly<FormProps<any, RJSFSchema, any>> & Readonly<...>'.
Property 'schema' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Form<any, RJSFSchema, any>> & Readonly<FormProps<any, RJSFSchema, any>> & Readonly<...>'. Did you mean 'uiSchema'?ts(2322)
And the other issue is this:

Nuxt Auth Custom Scheme with local strategies using Bearer Authorization

I want to make a custom scheme with local strategies but I don't know how can I do it using customScheme. Documentation of nuxt/auth v5 doest not help me
I want to execute two endpoint:
1st- request
POST /oauth/v2/token
HEAD:
Content-Type: application/x-www-form-urlencoded
body of the request:
clientId : string
clientSecret: string
grantType: string
username: string
password: string
response:
{
"accessToken": "string",
"expireTime": "2022-01-10T20:29:10.721Z",
"refreshToken": "string"
}
2nd- request
GET /security/users/me
HEAD
x-locale: fr|en
authorization: Bearer <TOKEN>
response:
{
"username": "string",
"firstname": "string",
"lastname": "string",
"email": "string",
"phone": "string",
"locale": "fr",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"expiresAt": "2022-01-10T20:38:36.478Z",
"loggedAt": "2022-01-10T20:38:36.478Z",
"roles": [
{
"name": "string",
"description": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string",
"description": "string"
},
"en": {
"name": "string",
"description": "string"
}
},
"permissions": [
{
"id": 1,
"code": "string",
"endUI": {
"name": "string",
"title": "string",
"id": 1,
"code": "string",
"type": {
"name": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string"
},
"en": {
"name": "string"
}
}
},
"module": {
"name": "string",
"description": "string",
"code": "string",
"id": 1,
"enabled": true,
"createdAt": "2022-01-10T20:38:36.478Z",
"updatedAt": "2022-01-10T20:38:36.478Z",
"translations": {
"fr": {
"name": "string",
"description": "string"
},
"en": {
"name": "string",
"description": "string"
}
}
},
"icon": "string",
"uri": "string",
"translations": {
"fr": {
"name": "string",
"title": "string"
},
"en": {
"name": "string",
"title": "string"
}
}
}
}
]
}
],
"avatar": {
"id": 1,
"url": "string"
}
}
nuxt.config.js
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
'#nuxtjs/dotenv',
'#nuxtjs/i18n', [
'nuxt-vuex-localstorage',
{
mode: 'debug',
localStorage: [
'user',
'service',
'location',
'storeType',
'warehouse',
'openingRange',
'store',
'holiday',
'taxon',
'provider',
'productOption',
'productAttribute',
'product',
'productVariant',
'glassesCatalog'
],
},
],
],
router: {
middleware: ['auth']
},
// Auth Strategies
auth: {
strategies: {
customStrategy: {
_scheme: '~/schemes/customScheme',
endpoints: {
login: {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: '/oauth/v2/token',
method: 'post'
},
user: {
url: '/security/users/me',
method: 'get',
propertyName: '',
headers: {
'x-locale': 'fr',
'Authorization': `Bearer ${It should be a token (accessToken) for the first request}`
}
}
}
}
}
}
~/schemes/customeScheme.js
import { LocalScheme } from '~auth/runtime'
export default class CustomScheme extends LocalScheme {
// Override `fetchUser` method of `local` scheme
async fetchUser (endpoint) {
// Token is required but not available
if (!this.check().valid) {
return
}
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Try to fetch user and then set
return this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
).then((response) => {
const user = getProp(response.data, this.options.user.property)
// Transform the user object
const customUser = {
...user,
fullName: user.firstName + ' ' + user.lastName,
roles: ['user']
}
// Set the custom user
// The `customUser` object will be accessible through `this.$auth.user`
// Like `this.$auth.user.fullName` or `this.$auth.user.roles`
this.$auth.setUser(customUser)
return response
}).catch((error) => {
this.$auth.callOnError(error, { method: 'fetchUser' })
})
}
}
~/login.vue
onSubmit(){
this.isSubmitting = true;
this.isDisabled= true;
let formData = new FormData();
formData.append("clientId", process.env.CLIENT_ID);
formData.append("clientSecret", process.env.CLIENT_SECRET);
formData.append("grantType", "password");
formData.append("username", this.dataUser.username);
formData.append("password", this.dataUser.password);
this.$refs.dataUser.validate(async (valid, fieldsError) => {
this.validate = valid;
if(valid){
try {
let response = await this.$auth.loginWith('customStrategy', { data: formData })
console.log(response);
this.$store.dispatch('storeSecurity/storeUserToken', response.data);
} catch (error) {
this.$message.error({content: this.$t("login.error"), key, duration: 3});
}
}
});
},
If I want to fetch user, how can i do please ???
everything I do gives me errors that have no answers in the doc
I need help please
You should use $auth.setUser(user) to set the current user after successfully login. That is iif your endpoints.user doesn't work.

Shoutem cloud - add new item from react-native part

I've created a new data schema (using shoutem schema command) that looks like this:
{
"name": "auditlog",
"title": "AuditLog",
"titleProperty": "name",
"type": "object",
"properties": {
"name": {
"format": "single-line",
"title": "Name",
"type": "string",
"displayPriority": 1
},
"type": {
"title": "Type",
"format": "single-line",
"type": "string",
"displayPriority": 2
},
"moreInfo": {
"title": "More Info",
"format": "object",
"type": "object",
"displayPriority": 3
}
}
}
I've connected it to admin pages like this:
"adminPages": [
{
"page": "shoutem.cms.CmsPage",
"title": "Audit Log",
"parameters": {
"schema": "#.AuditLog"
}
}
]
I tested adding a new item from the cms screen and it works perfectly.
Now I am trying to add a new item from react-native mobile app part using redux-io and create method like so:
const item = {
type: ext('AuditLog'),
attributes: {
name: 'Test',
type: 'get',
},
};
const config = {
schema: ext('AuditLog'),
request: {
headers: {
'Content-Type': 'application/vnd.api+json',
accept: 'application/vnd.api+json',
},
},
};
const createAction = create(config, item);
dispatch(createAction);
But when I try to do this, I get the following error:
{
"message":"403 - undefined",
"name":"ApiError",
"response":{
"errors":[
{
"code":"legacy_security_default",
"status":"403",
"title":"Forbidden."
}
]
}
}
Am I missing something that needs to be added to request?

validator not recognising property in oneOf

I'm building a schema that has a property with an enum and uses a oneOf to add properties and restrictions for each case of the enum. I'm getting an error about a missing property that is definitely not missing.
A reduced version of the schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://rc2.io/something",
"title": "Rc2 Compute Messages",
"type": "object",
"minProperties": 2,
"properties": {
"msg": {
"type": "string",
"description": "the command to perform",
"enum": ["close", "execScript"]
},
"argument": {
"type": "string",
"description": "main argument for the command"
}
},
"required": ["msg", "argument"],
"oneOf": [
{
"properties": {
"argument": { "maxLength": 0 },
"msg": { "const": "close"}
}
},
{
"properties": {
"msg": { "const": "execScript"},
"argument": { "minLength": 1 },
"queryId": { "type": "number", "multipleOf": 1.0, "minimum": 1 } },
"required": ["queryId"]
}
]
}
The json I'm trying to validate:
{
"queryId:": 2,
"argument": "testVar<-22",
"msg": "execScript"
}
The output from ajv:
[
{
keyword: 'maxLength',
dataPath: '.argument',
schemaPath: '#/oneOf/0/properties/argument/maxLength',
params: { limit: 0 },
message: 'should NOT be longer than 0 characters'
},
{
keyword: 'required',
dataPath: '',
schemaPath: '#/oneOf/1/required',
params: { missingProperty: 'queryId' },
message: "should have required property 'queryId'"
},
{
keyword: 'oneOf',
dataPath: '',
schemaPath: '#/oneOf',
params: { passingSchemas: null },
message: 'should match exactly one schema in oneOf'
}
]
Why is it not recognizing queryId?
Maybe because of this simple typo "queryId:" in your JSON data? Please note the extra colon after queryId.

Pass an already existing Model to next in Loopback

There is Project model
{
"name": "Project",
"plural": "Projects",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
},
"code": {
"type": "string"
},
"startDate": {
"type": "date",
"required": true
},
"endDate": {
"type": "date"
},
"value": {
"type": "number"
},
"infoEN": {
"type": "string"
},
"infoRU": {
"type": "string"
},
"infoAM": {
"type": "string"
},
"externalLinks": {
"type": [
"string"
]
}
},
"validations": [],
"relations": {
"industry": {
"type": "belongsTo",
"model": "Industry",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"service": {
"type": "belongsTo",
"model": "Service",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"tags": {
"type": "hasAndBelongsToMany",
"model": "Tag",
"foreignKey": "",
"options": {
"nestRemoting": true
}
}
},
"acls": [],
"methods": {}
}
And it hasAndBelongsToMany tags
here is Tag model
{
"name": "Tag",
"plural": "Tags",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Now when the relation is created loopback api gives this api endpoint.
POST /Projects/{id}/tags
This creates a new tag into the tags collection and adds it to the project.
But what about adding an already existing tag to the project?
So I figured maybe I add before save hook to the Tag
Here I'll check if the tag exists and then pass the existing one for the relation.
Something like this.
tag.js
'use strict';
module.exports = function(Tag) {
Tag.observe('before save', function(ctx, next) {
console.log(ctx.instance);
Tag.find({name: ctx.instance.name})
next();
});
// Tag.validatesUniquenessOf('name', {message: 'name is not unique'});
};
#HaykSafaryan it just demo to show you how to use tag inside project
var app = require('../../server/server');
module.exports = function(project) {
var tag=app.models.tags
//afterremote it just demo. you can use any method
project.afterRemote('create', function(ctx, next) {
tag.find({name: ctx.instance.name},function(err,result)){
if(err) throw err;
next()
}
});
};
this is just example code to show you how to use update,create ,find ,upsertwithwhere etc. tag for validation you have to setup condition over here it will not take validation which you defined in tags models