Argument userId: Got invalid value '5106220' on Prisma.findManyTodos. Provided String, expected IntFilter or Int: - next.js

using next.js +next-auth + Prisma + PostgreSQL
I added a custom login page and added the providers as well.
my userId in the database is Int so when I log in with credentials I have no issue but when logging in with one of the social providers I get an error...
Argument userId: Got invalid value '5106220' on Prisma.findManyTodos. Provided String, expected IntFilter or Int:
how to force providers to use Int instead of String when connecting to a database.
This error occurs whenever i need to connect the database
This is a Full error
provider: {
id: 'facebook',
name: 'Facebook',
type: 'oauth',
authorization: {
url: 'https://www.facebook.com/v11.0/dialog/oauth',
params: [Object]
},
token: {
url: 'https://graph.facebook.com/oauth/access_token',
params: {}
},
userinfo: {
url: 'https://graph.facebook.com/me',
params: [Object],
request: [AsyncFunction: request]
},
profile: [Function: profile],
idToken: false,
checks: [ 'state' ],
clientId: 'MyClientId',
clientSecret: '413db228b5b8e2e1134f5',
signinUrl: 'http://localhost:3000/api/auth/signin/facebook',
callbackUrl: 'http://localhost:3000/api/auth/callback/facebook'
}
}
[next-auth][debug][PROFILE_DATA] {
OAuthProfile: {
id: '11062270',
name: 'obi ',
email: 'ow1#gmail.com',
picture: { data: [Object] }
}
}
[next-auth][debug][OAUTH_CALLBACK_RESPONSE] {
profile: {
id: '5062260',
name: ' Eco',
email: 'ow1#gmail.com',
image: 'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=570&height=50&width=50&e&hash=AeR6hTT03RbzF9Z9hkg'
},
account: {
provider: 'facebook',
type: 'oauth',
providerAccountId: '0711062270',
access_token: 'EAAVmjxtUcOMBACPeAQm3Ocb0zzKcl8uiZAnZCYhhYxGo',
token_type: 'bearer',
expires_at: 1669548134
},
OAuthProfile: {
id: '560',
name: 'co',
email: 'ow1#gmail.com',
picture: { data: [Object] }
}
}
{
user: {
name: 'co',
email: 'ow1#gmail.com',
image: 'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=5007110622680570&height=50&width=50&ext=1666977090&hash=AeR6hTT03RbzF9Z9hkg',
id: '106226'
},
expires: '2022-10-28T17:11:31.515Z',
id: '1062'
}
PrismaClientValidationError:
Invalid `prisma.todos.findMany()` invocation:
{
where: {
userId: '7110620'
~~~~~~~~~~~~~~~~~~
},
select: {
id: true,
text: true,
done: true
}
}
Argument userId: Got invalid value '5106220' on prisma.findManyTodos. Provided String, expected IntFilter or Int:
type IntFilter {
equals?: Int
in?: List<Int>
notIn?: List<Int>
lt?: Int
lte?: Int
gt?: Int
gte?: Int
not?: Int | NestedIntFilter
}
type IntFilter {
equals?: Int
in?: List<Int>
notIn?: List<Int>
lt?: Int
lte?: Int
gt?: Int
gte?: Int
not?: Int | NestedIntFilter
}
at Document.validate (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:29297:20)
at serializationFn (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31876:19)
at runInChildSpan (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:25100:12)
at PrismaClient._executeRequest (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31883:31)
at consumer (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31810:23)
at C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31815:51
at AsyncResource.runInAsyncScope (node:async_hooks:201:9)
at C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31815:29
at runInChildSpan (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:25100:12)
at PrismaClient._request (C:\Users\elear\Desktop\TokTok4u\node_modules\#prisma\client\runtime\index.js:31812:22) {
clientVersion: '4.4.0'
}
API resolved without sending a response for /api/v1/todo/get, this may result in stalled requests.

According to the Prisma adapter in the NextAuth docs, the User model in the Prisma schema needs to have an id field with a String type.

You must add + before the field.
Example +id or +productId and try again.
This helps me resolve my problem.

Related

How to fix 'RealmObject cannot be called as a function' realm-js error?

In a react-native project using Realm-js, I've just created a clone of the app, integrated all libs, and copied over all src directories.
The app builds installs and runs on Android.
When i go through the authentication flow (which utilizes realm to store auth data), i ultimately get an error:
[ Error: RealmObject cannot be called as a function ]
login function:
async function login(username, password) {
try {
const result = await Api.login({
username: username,
pass: password,
});
const userAuthResult = await Db.updateAuth(result);
setUserAuth(userAuthResult);
} catch (err) {
console.log('[ ERROR ]:', err)
if (!err.message || err.message.includes('Network Error')) {
throw new Error('Connection error');
}
throw new Error('Wrong username or password');
}
}
and ive narrowed down the issue to Db.updateAuth(...)
updateAuth:
export const updateAuth = (params) => {
console.log(' [ HERE 1 ]')
const auth = {
id: params.id,
token: params.token,
refreshToken: params.refresh_token,
tokenExpiresAt: Math.floor(Date.now() / 1000) + 600, //params.expires_at,
federatedToken: params.federatedToken ?? '',
federatedTokenExpiresAt: params.federatedTokenExpiresAt ?? 0,
username: params.username,
name: params.name,
roleName: params.role_name,
roleId: params.role_id,
lastLogin: Math.floor(Date.now() / 1000),
};
console.log(' [ HERE 2 ]')
realm.write(() => {
console.log(' [ HERE 3 ]')
realm.create('Authorizations', auth, 'modified'); // PROBLEM
});
return auth;
};
inspecting the schema, i found theres no federatedToken propereties, yet in the auth update object, there are two. not sure why it wouldnt be throwing an error in the original non-cloned app.
authorizations schema:
AuthorizationsSchema.schema = {
name: 'Authorizations',
primaryKey: 'id',
properties: {
id: 'int',
token: 'string',
refreshToken: 'string',
tokenExpiresAt: 'int',
username: 'string',
name: 'string',
roleName: 'string',
roleId: 'int',
lastLogin: 'int',
},
};
Realm.js (class declaration) -> https://pastebin.pl/view/c903b2e2
from realm instantiation:
let realm = new Realm({
schema: [
schema.AccountSchema,
schema.AuthorizationsSchema,
schema.AvailableServiceSchema,
schema.FederatedTokensSchema,
schema.NoteSchema,
schema.PhotoSchema,
schema.PhotoUploadSchema,
schema.PrintQueueSchema,
schema.ProductSchema,
schema.ReportSchema,
schema.ServicesSchema,
schema.UploadQueueJobSchema,
schema.InvoicesSchema,
schema.TestSchema
],
schemaVersion: 60,
deleteRealmIfMigrationNeeded: true,
//path: './myrealm/data',
});
this logs the 1, 2, and 3 statements. The issue seems to come from the 'problem' line. Im not sure what exactly this error means, as there doesnt seem to be anything in realm's repo about it, and in the app this was cloned from, there was no issue with this line. I can also see other lines are throwing similar errors later on the user flows
Anyone know what this is about? or where i can learn more?
React-native: v64.2
realm-js: 10.6.0 (app cloned from was v10.2.0)
MacOS: 11.3 (M1 architecture)
in order to create you have the first call, the realm.write a method like this.
const storeInDataBase = (res,selectedfile) => {
try{
realm.write(() => {
var ID =
realm.objects(DocumentConverstionHistory).sorted('HistoryID', true).length > 0
? realm.objects(DocumentConverstionHistory).sorted('HistoryID', true)[0]
.HistoryID + 1
: 1;
realm.create(DocumentConverstionHistory, {
HistoryID: ID,
Name:`${selectedfile.displayname}.pdf`,
Uri:`file://${res.path()}`,
Date: `${new Date()}`
});
})
}catch(err){
alert(err.message)
}
}
Here is the schema file
export const DATABASENAME = 'documentconverter.realm';
export const DocumentConverstionHistory = "DocumentConverstionHistory"
export const DocumentConverstionHistorySchema = {
name: "DocumentConverstionHistory",
primaryKey: 'HistoryID',
properties: {
HistoryID: {type: 'int'},
Name: {type: 'string'},
Uri: {type: 'string?'},
Type: {type: 'string?'},
Size: {type: 'string?'},
Date: {type: 'date?'}
}
};

A property of AWS Amplify Graphql schema is missing even though it does exist

I am using AWS Amplify and want to add new data into AWS AppSync. Below is the schema that I have:
type Product
#model
#auth(rules: [{ allow: owner, ownerField: "userId" }, { allow: groups, groups: ["admin"] }]) {
id: Int
userId: ID
owner: String
title: String
}
type UpsellRule
#model
#auth(rules: [{ allow: owner, ownerField: "userId" }, { allow: groups, groups: ["admin"] }]) {
id: String
userId: ID
owner: String
name: String
subscriptionProducts: [Product]
upsellProducts: [Product]
}
Based on that schema, this is the mutation that I have to add a new item:
const createUpsellRule = `mutation CreateUpsellRule($input: CreateUpsellRuleInput!) {
createUpsellRule(input: $input) {
id
userId
owner
name
subscriptionProducts {
id
userId
owner
title
}
upsellProducts {
id
userId
owner
title
}
}
}
This is an example of the payload that I sent:
{
id: '<a-unique-id>',
userId: '<a-unique-userId>',
owner: '<an-owner>',
subscriptionProducts: [{
userId: '89217803-5fff-44d9-93af-e72b05012813',
owner: '<an-owner>',
id: 4448795164753,
name: 'Product 10'
},
{
userId: '89217803-5fff-44d9-93af-e72b05012813',
owner: '<an-owner>',
id: 4448795656273,
name: 'Product 11'
}
],
upsellProducts: [{
userId: '89217803-5fff-44d9-93af-e72b05012813',
owner: '<an-owner>',
id: 4448796573777,
title: 'Product 13'
}],
name: 'ALL'
}
Using above schema, mutation, and payload, I got an error that saying subscriptionProducts field is not defined. To make sure that the schema is correct, I try to exclude subscriptionProducts and upsellProducts and it successfully added into AppSync. When I try to get it again from the AppSync, it shown me subscriptionProducts and upsellProducts properties which have null as a value. Do anyone of you know what is the correct mutation / payload that I should use based on the schema above?
PS: I am using aws-appsync as a client library

AppSync batch insert to DynamoDB fails and returns null

I have the following resolver settings:
#set($questions = [])
#foreach($item in ${ctx.args.questions})
#set($item.id = $util.dynamodb.toDynamoDBJson($util.autoId()))
$util.qr($questions.add($util.dynamodb.toMapValues($item)))
#end
{
"version" : "2018-05-29",
"operation" : "BatchPutItem",
"tables" : {
"QuestionTable": $utils.toJson($questions)
}
}
And the following GraphQL schema:
input CreateQuestionInput {
text: String
sectionId: ID!
}
input CreateScoreInput {
score: Int!
questionId: ID!
userId: ID!
}
input CreateSectionInput {
title: String
subSection: String
}
input DeleteQuestionInput {
id: ID!
}
input DeleteScoreInput {
id: ID!
}
input DeleteSectionInput {
id: ID!
}
type Mutation {
...
createQuestion(input: CreateQuestionInput!): Question
batchCreateQuestion(questions: [CreateQuestionInput]!): [Question]
}
type Query {
getSection(id: ID!): Section
listSections(filter: TableSectionFilterInput, limit: Int, nextToken: String): SectionConnection
getScore(id: ID!): Score
listScores(filter: TableScoreFilterInput, limit: Int, nextToken: String): ScoreConnection
getQuestion(id: ID!): Question
listQuestions(filter: TableQuestionFilterInput, limit: Int, nextToken: String): QuestionConnection
}
type Question {
id: ID!
text: String
sectionId: ID!
}
type QuestionConnection {
items: [Question]
nextToken: String
}
type Schema {
query: Query
}
type Score {
id: ID!
score: Int!
questionId: ID!
userId: ID!
}
type ScoreConnection {
items: [Score]
nextToken: String
}
type Section {
id: ID!
title: String
subSection: String
questions: [Question]
}
type SectionConnection {
items: [Section]
nextToken: String
}
input TableQuestionFilterInput {
id: TableIDFilterInput
text: TableStringFilterInput
sectionId: TableIDFilterInput
}
input UpdateQuestionInput {
id: ID!
text: String
sectionId: ID
}
(I've redacted some of the schema as it was fairly large).
When I attempt to run the query:
mutation BatchCreateQuestions($sec: ID!) {
batchCreateQuestion(questions: [
{
text: "Tester 1"
sectionId: $sec
},
{
text: "Tester 2",
sectionId: $sec
}
]) {
id
text
sectionId
}
}
With the variables:
{ "sec": "abc123" }
I get the response:
{
"data": {
"batchCreateQuestion": [
null,
null
]
}
}
And when I check the DynamoDB table, it hasn't saved the values. I've granted full dynamodb permissions for this datasource, but still no joy.
Turns out I'd given batch write permissions to a similarly named role instead of the role affecting this data source. If you see a similar issue, check your IAM roles/permissions. Silly me.
What does your response template look like in the resolver? It should be $util.toJson($ctx.result.data.QuestionTable) based on the above table name being QuestionTable as that gets automatically translated into the response context.

Apollo/GraphQL: Setting Up Resolver for String Fields?

In GraphiQL at http://localhost:8080/graphiql, I'm using this query:
{
instant_message(fromID: "1"){
fromID
toID
msgText
}
}
I'm getting this response:
{
"data": {
"instant_message": {
"fromID": null,
"toID": null,
"msgText": null
}
},
"errors": [
{
"message": "Resolve function for \"instant_message.fromID\" returned undefined",
"locations": [
{
"line": 3,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.toID\" returned undefined",
"locations": [
{
"line": 4,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.msgText\" returned undefined",
"locations": [
{
"line": 5,
"column": 5
}
]
}
]
}
I tried to set up my system according to the examples found here:
https://medium.com/apollo-stack/tutorial-building-a-graphql-server-cddaa023c035#.s7vjgjkb7
Looking at that article, it doesn't seem to be necessary to set up individual resolvers for string fields, but I must be missing something.
What is the correct way to update my resolvers so as to return results from string fields? Example code would be greatly appreciated!
Thanks very much in advance to all for any thoughts or info.
CONNECTORS
import Sequelize from 'sequelize';
//SQL CONNECTORS
const db = new Sequelize(Meteor.settings.postgres.current_dev_system.dbname, Meteor.settings.postgres.current_dev_system.dbuser, Meteor.settings.postgres.current_dev_system.dbpsd, {
host: 'localhost',
dialect: 'postgres',
});
db
.authenticate()
.then(function(err) {
console.log('Connection to Sequelize has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the Sequelize database:', err);
});
const IMModel = db.define('IM', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
fromID: {type: Sequelize.STRING},
toID: {type: Sequelize.STRING},
msgText: {type: Sequelize.STRING}
});
IMModel.sync({force: true}).then(function () {
// Table created
return IMModel.create({
fromID: '1',
toID: '2',
msgText: 'msg set up via IMModel.create'
});
});
const IM = db.models.IM;
export {db, IM };
SCHEMA
const typeDefinitions = [`
type instant_message {
id: Int
fromID: String
toID: String
msgText: String
}
type Query {
instant_message(fromID: String, toID: String, msgText: String): instant_message
}
type RootMutation {
createInstant_message(
fromID: String!
toID: String!
msgText: String!
): instant_message
}
schema {
query: Query,
mutation: RootMutation
}
`];
export default typeDefinitions;
RESOLVERS
import * as connectors from './db-connectors';
import { Kind } from 'graphql/language';
const b = 100;
const resolvers = {
Query: {
instant_message(_, args) {
const a = 100;
return connectors.IM.find({ where: args });
}
},
RootMutation: {
createInstant_message: (__, args) => { return connectors.IM.create(args); },
},
};
export default resolvers;
When you define your GraphQLObjectTypes you need to provide a resolver for each of their fields.
You defined your instant_message with multiple fields but did not provide resolvers for each of these fields.
More over you defined the types of those field with regular typescript fields while you need to define it with GraphQL types (GraphQLInt, GraphQLString, GrapQLFloat etc..)
So defining your type should look something like this:
let instant_message = new GraphQLObjectType({
id: {
type: GraphQLInt,
resolve: (instantMsg)=> {return instantMsg.id}
}
fromID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.fromID}
}
toID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.toID}
}
msgText: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.msgText}
}
})
In addition, you will need to define your Query as follows:
let Query = new GraphQLObjectType({
name: "query",
description: "...",
fields: () => ({
instant_messages: {
type: new GraphQLList(instant_message),
args: {
id: {type: GraphQLInt}
},
resolve: (root, args) => {
connectors.IM.find({ where: args })
}
}
})
})
The issue is that the query does not expect an array,
Please fix it:
type Query {
instant_message(fromID: String, toID: String, msgText: String): [instant_message]
}
Then you should make sure the resolver returns Array of objects, if it doesnt work then the resolver is not returning an Array.

Meteor aldeed/meteor-collection2 autoValue throwing error

I am trying to use autoValue in my schema
Posts.schema = new SimpleSchema({
title: { type: String },
description: { type: String },
posted: { type: Date,
autoValue: function (){
return new Date;
},
},
likes: { type: Number, defaultValue: 0, optional: true },
dislikes: { type: Number, defaultValue: 0, optional: true, },
author: { type: AuthorSchema },
votes: { type: [AuthorSchema], optional: true }
});
Posts.attachSchema(Posts.schema);
I am using this schema for validations here:
export const addPost = new ValidatedMethod({
name: 'Posts.addPost',
validate: Posts.schema.validator(),
run(post) {
if (!this.userId)
throw new Meteor.Error('403', 'You must be logged-in to reply');
Posts.simpleSchema().clean(post);
Posts.insert({
title: post.title,
description: post.description,
author: {
userId: this.userId,
vote: 0
}
});
}
});
It does not work. I get an error message
Posted is required [validation-error]
Am i doing something wrong? Do i need to make Posted field optional?
I tried to change the insert method by providing default value for posted: new Date(). Did not work either. Please help.
Fixed it by calling validator with { clean : true, filter : false }

Resources