React jsonschema form - schema does not exist on property type - jsonschema

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:

Related

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.

Realm sync not working for embedded objects in 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.

Why isn't Swagger detecting optional JSON properties?

I have the following class:
import com.fasterxml.jackson.annotation.JsonProperty
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
data class Entity(
val email: String,
val name: String,
val birthDate: DateTime,
#JsonProperty(required = false) val gender: Gender? = null,
#JsonProperty(required = false) val country: String? = null,
val locale: String,
val disabled: Boolean = false,
#JsonProperty(required = false) val createdAt: DateTime = DateTime(DateTimeZone.UTC),
val role: Role,
val entityTypeId: Long,
val entityTypeAttributes: MutableMap<String, Any> = HashMap(),
val medicalSpecialityId: Long? = null,
val id: Long? = null
)
And some properties are not required, because they are either nullable (gender, country), or they have a default value (createdAt).
However, the generated swagger documentation is as follows:
"components": {
"schemas": {
"Entity": {
"required": [
"birthDate",
"createdAt", <------------ Notice here!
"disabled",
"email",
"entityTypeAttributes",
"entityTypeId",
"locale",
"name",
"role"
],
"type": "object",
"properties": {
"email": {
"type": "string"
},
"name": {
"type": "string"
},
"birthDate": {
"type": "string",
"format": "date-time"
},
"gender": {
"type": "string",
"enum": [
"MALE",
"FEMALE",
"OTHER"
]
},
"country": {
"type": "string"
},
"locale": {
"type": "string"
},
"disabled": {
"type": "boolean"
},
"createdAt": {
"type": "string",
"format": "date-time"
},
"role": {
"type": "string",
"enum": [
"ADMIN",
"DOCTOR",
"PATIENT"
]
},
"entityTypeId": {
"type": "integer",
"format": "int64"
},
"entityTypeAttributes": {
"type": "object",
"additionalProperties": {
"type": "object"
}
},
"medicalSpecialityId": {
"type": "integer",
"format": "int64"
},
"id": {
"type": "integer",
"format": "int64"
}
}
},
(...)
So in terms of documentation it shows that createdAt is mandatory (which is not true)...
Generated Swagger docs
I am using Kotlin, Javalin and the OpenAPI (io.javalin.plugin.openapi) Javalin integration.
I don't know what more do I need to make OpenAPI understand that createdAt is optional...
My guess would be that the kotlin implementation is using nullability as a way to discover required and ignoring the required property. For example, you shouldn't actually need the annotation for gender and country.
Obviously this is not ideal, but if you change creadtedAt to a DateTime? it would not show as required.
This is likely a bug with the kotlin openapi doc tool that javalin has pulled in.

Why oneOf does not work on my schema in jsonschema?

My login has different payloads one is:
{
"username": "",
"pass": ""
}
And one of the other is:
{
"username": "",
"pass": "",
"facebook": true
}
And the last:
{
"username": "",
"pass": "",
"google": true
}
My schema is as follow:
login_schema = {
"title": "UserLogin",
"description": "User login with facebook, google or regular login.",
"type": "object",
"properties": {
"username": {
"type": "string"
},
"pass": {
"type": "string"
},
"facebook": {
"type": "string"
},
"google": {
"type": "string"
}
},
"oneOf": [
{
"required": [
"username",
"pass"
],
"additionalProperties": False,
},
{
"required": [
"username",
"pass"
"google"
]
},
{
"required": [
"username",
"pass",
"facebook"
]
}
],
"minProperties": 2,
"additionalProperties": False,
}
It should give an error for the below sample:
{
"username": "",
"pass": "",
"google": "",
"facebook": ""
}
But it validates the schema successfully! What I have done wrong in the above schema?
EDIT-1:
pip3 show jsonschema
Name: jsonschema
Version: 3.0.2
Summary: An implementation of JSON Schema validation for Python
Home-page: https://github.com/Julian/jsonschema
Author: Julian Berman
Author-email: Julian#GrayVines.com
License: UNKNOWN
Location: /usr/local/lib/python3.7/site-packages
Requires: setuptools, six, attrs, pyrsistent
EDIT-2:
What I get as an error is:
jsonschema.exceptions.ValidationError: {'username': '', 'pass': '', 'google': '12'} is valid under each of {'required': ['username', 'pass', 'google']}, {'required': ['username', 'pass']}
A live demo of the error: https://jsonschema.dev/s/mXg5X
Your solution is really close. You just need to change /oneOf/0 to
{
"properties": {
"username": true,
"pass": true
},
"required": ["username", "pass"],
"additionalProperties": false
}
The problem is that additionalProperties doesn't consider the required keyword when determining what properties are considered "additional". It considers only properties and patternProperties. When just using required, additionalProperties considers all properties to be "additional" and the only valid value is {}.
However, I suggest a different approach. The dependencies keyword is useful in these situations.
{
"type": "object",
"properties": {
"username": { "type": "string" },
"pass": { "type": "string" },
"facebook": { "type": "boolean" },
"google": { "type": "boolean" }
},
"required": ["username", "pass"],
"dependencies": {
"facebook": { "not": { "required": ["google"] } },
"google": { "not": { "required": ["facebook"] } }
},
"additionalProperties": false
}

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