i am using prisma image 1.34
I have a small issue trying to implement the prisma.exists method with mongodb atlas.
type Business {
_id: ID! #id
name: String!
desc: String!
published: Boolean!
author: User! #relation(name: "BusinessUser", link: INLINE)
async updateBusiness(parent, args, { prisma, request }, info) {
const postExists = await prisma.exists.Business({
_id: args.id,
})
if (!postExists) {
throw new Error('Unable to update post')
}
return prisma.mutation.updateBusiness({
where: {
_id: args.id
},
data: args.data
}, info)
}
}
the error I got is
TypeError: Cannot read property 'length' of undefined
at C:\Users\jarid\Desktop\Alfarouk\alfarouq\Backend\node_modules\prisma-binding\src\Prisma.ts:86:31
at process._tickCallback (internal/process/next_tick.js:68:7)
when I remove the code related to prisma.exists the resolver runs successfully , also I did verify that the argument "args.id" is pulled successfully
**Versions
Prisma Server: [1.34.1]
prisma CLI: [1.34.1 ]
OS: [Windows 10 home edition]
docker toolbox
Are you using the client or the bindings? According to the prisma documentation the syntax should be as follows:
const userExists = prisma.$exists.user({
id: 'cjli6tko8005t0a23fid7kke7',
})
See: https://www.prisma.io/docs/1.34/prisma-client/features/check-existence-JAVASCRIPT-pyl1/
I had the same problem. The Documentation is not correct.
The exists function is called in the wrong way.
Try this. it should work...
const userExists = prisma.user({
id: 'cjli6tko8005t0a23fid7kke7',
}).$exists
Related
I'm using AWS CDK version 2.64.0 to configure AWS AppSync to setup my GraphQL API.
I created my graphql.schema with the following configuration:
type message {
id_message: String!
id_collection: String!
id_user: String!
created_at: String!
text: String!
}
type Query {
getMessages(idCollectionIdUser: String!): [ message! ]
}
And then I used the configuration above to create my GraphQL API using these commands:
const api = new appsync.GraphqlApi(this, 'GraphQLDatabase', {
name: 'my-graphql-database',
schema: appsync.SchemaFile.fromAsset(path.join(__dirname, 'schema.graphql')),
xrayEnabled: true,
});
I also created one dynamodb table (with one global secondary index) using the following commands:
const messageTable = new dynamodb.Table(this, 'MessageTable', {
partitionKey: {
name: 'id_message',
type: dynamodb.AttributeType.STRING,
},
tableName: 'message.dynamodb-table',
removalPolicy: RemovalPolicy.DESTROY,
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});
messageTable.addGlobalSecondaryIndex({
indexName: 'id_collection-id_user-created_at-index',
partitionKey: {
name: 'id_collection-id_user',
type: dynamodb.AttributeType.STRING,
},
sortKey: {
name: 'created_at',
type: dynamodb.AttributeType.NUMBER,
},
projectionType: ProjectionType.ALL,
});
Then I added the dynamodb table as datasource for the graphql database:
const messageDataSource = api.addDynamoDbDataSource('messageDataSource', messageTable);
I'm now trying to create a resolver to get all the messages created by the user in a collection with the following code:
messageDataSource.createResolver('QueryGetMessagesResolver', {
typeName: 'Query',
fieldName: 'getMessages',
requestMappingTemplate: appsync.MappingTemplate.dynamoDbQuery(
appsync.KeyCondition.eq('id_collection-id_user', 'idCollectionIdUser'),
'id_collection-id_user-created_at-index',
false,
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(),
});
When I test my graph api, I always get this error:
ExpressionAttributeNames contains invalid key: Syntax error; key: "#id_collection-id_user"
What am I doing wrong?
I want to create a post with a list of tags attached to it. The models are connected many-to-many (one post can have several tags, and one tag can have several posts in it).
Here are my prisma models:
model Post {
id String #id #default(cuid())
slug String #unique
title String
body String
tags Tag[]
}
model Tag {
id String #id #default(cuid())
posts Post[]
name String
slug String #unique
}
And here's a mutation where I'm trying to create a post, and attach tags to it:
t.field('createPost', {
type: 'Post',
args: {
title: nonNull(stringArg()),
body: stringArg(),
tags: list(arg({ type: 'TagInput' }))
},
resolve: async (_, args, context: Context) => {
// Create tags if they don't exist
const tags = await Promise.all(
args.tags.map((tag) =>
context.prisma.tag.upsert({
create: omit(tag, "id"),
update: tag,
where: { id: tag.id || "" },
})
)
)
return context.prisma.post.create({
data: {
title: args.title,
body: args.body,
slug: `${slugify(args.title)}-${cuid()}`,
// Trying to connect a post to an already existing tag
// Without the "tags: {...} everything works
tags: {
set: [{id:"ckql6n0i40000of9yzi6d8bv5"}]
},
authorId: getUserId(context),
published: true, // make it false once Edit post works.
},
})
},
})
This doesn't seem to be working.
I'm getting an error:
Invalid `prisma.post.create()` invocation:
{
data: {
title: 'Post with tags',
body: 'Post with tags body',
slug: 'Post-with-tags-ckql7jy850003uz9y8xri51zf',
tags: {
connect: [
{
id: 'ckql6n0i40000of9yzi6d8bv5'
}
]
},
}
}
Unknown arg `tags` in data.tags for type PostUncheckedCreateInput. Available args:
type PostUncheckedCreateInput {
id?: String
title: String
body: String
slug: String
}
It seems like the tags field on the post is missing? But I did run prisma generate and prisma migrate. Also I can successfully query tags on a post if I add them manually using Prisma Studio. What could be causing this issue?
You need to use connect for the author as well. So the following will work fine:
return context.prisma.post.create({
data: {
title: args.title,
body: args.body,
slug: `${slugify(args.title)}-${cuid()}`,
// Trying to connect a post to an already existing tag
// Without the "tags: {...} everything works
tags: {
set: [{id:"ckql6n0i40000of9yzi6d8bv5"}]
},
author: { connect: { id: getUserId(context) } },
published: true, // make it false once Edit post works.
},
})
In my case, the issue arose when I created a new field on the prisma model called uid and tried to run the command prisma migrate dev
It brought the error
Error:
⚠️ We found changes that cannot be executed:
• Step 0 Added the required column `uid` to the `Transactions` table without a default value. There are 1 rows in this table, it is not possible to execute this step.
You can use prisma migrate dev --create-only to create the migration file, and manually modify it to address the underlying issue(s).
Then run prisma migrate dev to apply it and verify it works.
I solved it by adding the #default("") to it.
model Transactions {
id Int #id #default(autoincrement())
uid String #default("")
account String
description String
category String
reference String
currency String #default("GBP")
amount String
status String
transactionDate String
createdAt String
updatedAt String
}
I'm trying to get an interface working with the new #fileByRelativePath resolver extension, to keep compatible with v3.
I'm using Prismic for my content, and gatsby-source-prismic v2. I have two content types in Prismic, and created the interface to be able to more easily query and map over both for a home page index.
Here's the functioning (but with deprecated inferred resolvers) schema:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
interface indexPosts #nodeInterface {
id: ID!
uid: String!
data: Data!
type: String!
}
type Data {
title: Title!
date: Date!
featured: String!
featured_image: Featured_image!
body: Body!
}
type Title {
text: String!
}
type Featured_image {
localFile: File!
}
type Body {
html: String!
}
type PrismicGallery implements Node & indexPosts {
uid: String!
data: Data!
type: String!
}
type PrismicEssay implements Node & indexPosts {
uid: String!
data: Data!
type: String!
}
`
createTypes(typeDefs)
}
The problem comes after adding #fileByRelativePath to the Featured_image type definition. Doing so gives me an error during build:
"The "path" argument must be of type string. Received type undefined"
I'm unsure how to provide the necessary path argument, considering my images are third-party hosted. I'm trying to follow the brief guide at the end of this page and suspect the way to do it might be with a resolver or type builder and using 'source' to access the url field provided by both localFile and its parent, featured_image, but I can't figure it out!
I'm using gatsby-image and the childImageSharp convenience field to present the images, if that makes a difference at all!
I had exactly the same problem when I tried to use #fileByRelativePath. I managed to solve my problem by using #infer on the type that contained the File.
Try this:
type Featured_image #infer {
localFile: File!
}
Within my resolver I seem to be unable to fetch connected data
this works in the graphql playground (prisma) but I am unsure of the syntax about how to form a resolver in apollo server
// my typedef for activity is
type Activity {
id: ID! #id
ActivityType: ActivityType!
title: String!
date: DateTime
user: User!
distance: Float!
distance_unit: Unit!
duration: Float!
elevation: Float
elevation_unit: Unit
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
// and my resolver currently looks like this
async activity(parent, args, ctx, info) {
const foundActivity = await ctx.db.query.activity({
where: {
id: args.id
}
});
// todo fetch user data from query
console.log(foundActivity);
}
// where db has been placed onto the ctx (context)
// the CL gives all of the data for Activity apart from the user
// in the playground I would do something like this
query activity {
activity(where: {
id: "cjxxow7c8si4o0b5314f9ibek"
}){
title
user {
id
name
}
}
}
// but I do not know how to specify what is returned in my resolver.
console.log(foundActivity) gives:
{ id: 'cjxxpuh1bsq750b53psd2c77d',
ActivityType: 'CYCLING',
title: 'Test Activity',
date: '2019-07-10T20:21:27.681Z',
distance: 13.4,
distance_unit: 'KM',
duration: 90030,
elevation: 930,
elevation_unit: 'METERS',
createdAt: '2019-07-10T20:48:50.879Z',
updatedAt: '2019-07-10T20:48:50.879Z' }
Prisma is the DB ORM and then I have an Apollo-Server 2 server running on top of that. Unfortunately, stack overflow also thinks that there is too much code on this post so I will have to waffle on about inconsequential gibberish due to the fact that their system can't handle it.
You will have to implement a resolver for Activity.user. Unfortunately your entity does not seem to contain a reference to the user. First, add the user connection to your Prisma data model. Then implement a resolver for Activity.user. I am not very familiar with Prisma 1 but this naive implementation should already do what you want:
let resolvers = {
Query: {
// ...
},
Activity: {
user(parent, args, ctx) {
return ctx.db.query.activity({ id: parent.id }).user();
}
}
}
Find out more about resolving relations in Prisma here
So the answer was incredibly simple:
I just add a second argument to the query (after the "where" with a gql tag of the data shape to be returned so my code now looks like:
const foundActivity = await ctx.db.query.activity(
{
where: {
id: args.id
}
},
`{id title user { id name }}`
);
I am using Prisma with GraphQL and get errors when I run the mutatioin.
I deployed prisma succussfully and binded it with local graphQL.
-- datamodel.graphql - prisma setting
type Link {
id: ID! #unique
description: String!
url: String!
postedBy: User
}
type User {
id: ID! #unique
name: String!
email: String! #unique
password: String!
links: [Link!]!
}
-- schema.graphql - local setting
# import Link from "./generated/prisma.graphql"
type Query {
info: String!
feed: [Link!]!
}
type Mutation {
post(url: String!, description: String!): Link!
signup(email: String!, password: String!, name: String!): AuthPayload
login(email: String!, password: String!): AuthPayload
}
type AuthPayload {
token: String
user: User
}
type User {
id: ID!
name: String!
email: String!
links: [Link!]!
}
Resolver for signup mutation is
async function signup(parent, args, context, info) {
// 1
const password = await bcrypt.hash(args.password, 10)
// 2
const user = await context.db.mutation.createUser({
data: { ...args, password },
}, `{ id }`)
// 3
const token = jwt.sign({ userId: user.id }, APP_SECRET)
// 4
return {
token,
user,
}
}
And this is .graphqlconfig.yml content
projects:
app:
schemaPath: src/schema.graphql
extensions:
endpoints:
default: http://localhost:4000
database:
schemaPath: src/generated/prisma.graphql
extensions:
prisma: database/prisma.yml
GraphQL query I run is .
mutation {
signup(
name: "Alice"
email: "alice#graph.cool"
password: "graphql"
) {
token
user {
id
}
}
}
And the response I got when I run this is
{
"data": {
"signup": null
},
"errors": [
{
"message": "Variable '$_data' cannot be non input type 'UserCreateInput!'. (line 1, column 19):\nmutation ($_data: UserCreateInput!) {\n ^",
"locations": [],
"path": [
"createUser"
]
}
]
}
I can'find the reason of this.
Thank you.
Try use prisma deploy --force
This worked for me.
Fixed it by changing to the right endpoint in index.js
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
context: req => ({
...req,
db: new Prisma({
typeDefs: 'src/generated/prisma.graphql',
endpoint: 'http://localhost:4466/local/dev',
secret: 'secret',
debug: true,
}),
}),
})
I think your prisma.yml was wrong.
# The endpoint represents the HTTP endpoint for your Prisma API. It encodes
# several pieces of information:
# * Prisma server (`localhost:4466` in this example)
# * Service name (`myservice` in this example)
# * Stage (`dev` in this example)
# NOTE: When service name and stage are set to `default`, they can be omitted.
# Meaning http://myserver.com/default/default can be written as http://myserver.com.
endpoint: http://localhost:4466/myservice/dev