Subscriptions not working with Prisma 2 and Nexus? - javascript

Subscriptions with Nexus are undocumented but I searched Github and tried every example in the book. It's just not working for me.
I have cloned Prisma2 GraphQL boilerplate project & my files are as follows:
prisma/schema.prisma
datasource db {
provider = "sqlite"
url = "file:dev.db"
default = true
}
generator photon {
provider = "photonjs"
}
generator nexus_prisma {
provider = "nexus-prisma"
}
model Pokemon {
id String #default(cuid()) #id #unique
number Int #unique
name String
attacks PokemonAttack?
}
model PokemonAttack {
id Int #id
special Attack[]
}
model Attack {
id Int #id
name String
damage String
}
src/index.js
const { GraphQLServer } = require('graphql-yoga')
const { join } = require('path')
const { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('#prisma/nexus')
const Photon = require('#generated/photon')
const { nexusPrismaPlugin } = require('#generated/nexus-prisma')
const photon = new Photon()
const nexusPrisma = nexusPrismaPlugin({
photon: ctx => ctx.photon,
})
const Attack = objectType({
name: "Attack",
definition(t) {
t.model.id()
t.model.name()
t.model.damage()
}
})
const PokemonAttack = objectType({
name: "PokemonAttack",
definition(t) {
t.model.id()
t.model.special()
}
})
const Pokemon = objectType({
name: "Pokemon",
definition(t) {
t.model.id()
t.model.number()
t.model.name()
t.model.attacks()
}
})
const Query = objectType({
name: 'Query',
definition(t) {
t.crud.findManyPokemon({
alias: 'pokemons'
})
t.list.field('pokemon', {
type: 'Pokemon',
args: {
name: stringArg(),
},
resolve: (parent, { name }, ctx) => {
return ctx.photon.pokemon.findMany({
where: {
name
}
})
},
})
},
})
const Mutation = objectType({
name: 'Mutation',
definition(t) {
t.crud.createOnePokemon({ alias: 'addPokemon' })
},
})
const Subscription = subscriptionField('newPokemon', {
type: 'Pokemon',
subscribe: (parent, args, ctx) => {
return ctx.photon.$subscribe.pokemon()
},
resolve: payload => payload
})
const schema = makeSchema({
types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],
outputs: {
schema: join(__dirname, '/schema.graphql')
},
typegenAutoConfig: {
sources: [
{
source: '#generated/photon',
alias: 'photon',
},
],
},
})
const server = new GraphQLServer({
schema,
context: request => {
return {
...request,
photon,
}
},
})
server.start(() => console.log(`🚀 Server ready at http://localhost:4000`))
The related part is the Subscription which I don't know why it's not working or how it's supposed to work.
I searched Github for this query which results in all projects using Subscriptions.
I also found out this commit in this project to be relevant to my answer. Posting the related code here for brevity:
import { subscriptionField } from 'nexus';
import { idArg } from 'nexus/dist/core';
import { Context } from './types';
export const PollResultSubscription = subscriptionField('pollResult', {
type: 'AnswerSubscriptionPayload',
args: {
pollId: idArg(),
},
subscribe(_: any, { pollId }: { pollId: string }, context: Context) {
// Subscribe to changes on answers in the given poll
return context.prisma.$subscribe.answer({
node: { poll: { id: pollId } },
});
},
resolve(payload: any) {
return payload;
},
});
Which is similar to what I do. But they do have AnswerSubscriptionPayload & I don't get any generated type that contains Subscription in it.
How do I solve this? I think I am doing everything right but it's still not working. Every example on GitHub is similar to above & even I am doing the same thing.
Any suggestions?
Edit: Subscriptions aren't implemented yet :(

I seem to have got this working despite subscriptions not being implemented. I have a working pubsub proof of concept based off the prisma2 boilerplate and Ben Awad's video tutorial https://youtu.be/146AypcFvAU . Should be able to get this up and running with redis and websockets to handle subscriptions until the prisma2 version is ready.
https://github.com/ryanking1809/prisma2_subscriptions

Subscriptions aren't implemented yet.
I've opened up an issue to track it.
I'll edit this answer as soon as it's implemented in Prisma 2.

Related

How to create Gatsby Image data for nested nodes?

I am trying to use createRemoteFileNode to create optimised images for an array of nodes that exist on a Product.
I have a Product that has items and on each item, it has a featuredImg. I can create a featuredImg for a Product but as soon as I try to create it for the child nodes (items) then it is not queryable.
I am creating my nodes as such:
const products = [
{
id: "product_1",
imageUrl: "https://images.unsplash.com/photo-1665081661649-8656335a6cbb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1738&q=80",
items: [
{
id: 'item_1',
imageUrl: "https://images.unsplash.com/photo-1666120565124-7e763880444a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80"
}
]
}
]
const sourceNodes = async ({ actions, createNodeId, createContentDigest }, options) => {
products.forEach((testNode) => {
const node = {
...testNode,
id: createNodeId(`Product-${testNode.id}`),
}
actions.createNode({
...node,
internal: {
type: 'Product',
contentDigest: createContentDigest(node),
},
});
testNode.items.forEach(item => {
const itemNode = {
...item,
id: createNodeId(`Item-${item.id}`),
}
actions.createNode({
...itemNode,
parent: node.id,
internal: {
type: 'Item',
contentDigest: createContentDigest(itemNode),
},
});
})
})
};
module.exports = sourceNodes;
Then on the node creation, I am running the onCreateNode function which should create the remote file node for each item featuredImg.
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
const onCreateNode = async ({ node, cache, store, getCache, actions: { createNode, createNodeField }, createNodeId }) => {
if( node.internal.type === 'Item') {
const fileNode = await createRemoteFileNode({
url: node.imageUrl,
parentNodeId: node.parent,
createNode,
createNodeId,
getCache,
})
if (fileNode) {
createNodeField({ node, name: "localFile", value: fileNode.id })
}
}
if( node.internal.type === 'Product') {
const fileNode = await createRemoteFileNode({
url: node.imageUrl,
parentNodeId: node.id,
createNode,
createNodeId,
getCache,
})
if (fileNode) {
createNodeField({ node, name: "localFile", value: fileNode.id })
}
}
};
module.exports = onCreateNode
I have defined my types here:
module.exports = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type Product implements Node {
id: String!
imageUrl: String!
featuredImg: File #link(from: "fields.localFile")
items: [Item]
}
type Item implements Node {
id: String!
imageUrl: String!
featuredImg: File #link(from: "fields.localFile")
}
`;
createTypes(typeDefs);
};
For some reason, when I query Products.items[i].featuredImg it always returns null. However, I can see the node is generated because I can query item.featuredImg and it returns the gatsbyImageData.
I have created a simple example here and included a read me on how to replicate it: https://github.com/stretch0/gatsby-sandbox
I have also noticed that this post is a similar issue of not being able to create remote file nodes within a loop but because they have a different file structure, I can't figure out how their solution to use createSchemaCustomization or createResolvers would apply to my setup.

How to properly create defaults with apollo-link-state

I'm currently migrating an application I developed from redux to apollo. I'm following this example trying to implement apollo-link-state and apollo-cache-inmemory but I'm struggling to understand how their framework works. It would be great if someone could answer some questions, so here we go:
Use Case: Store modals information (basically wether it's open or not) in my cache memory
Here is my code:
// apollos.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink } from 'apollo-link';
import { modalStateQuery } from "./common/queries/modal.query";
const httpLinkOptions = {
uri: 'http://localhost:8080/graphql',
};
const httpLink = new HttpLink(httpLinkOptions);
const cache = new InMemoryCache({
dataIdFromObject: o => o.id
});
const typeDefs = `
type Modal {
id: ID!
open: Boolean!
}
type Query {
modal(id: ID!): Modal
modals: [Modal]
}
`;
const defaults = {
modals: [
{
__typename: "Modal",
id: "login",
open: false
},
{
__typename: "Modal",
id: "signup",
open: false
}
]
};
const resolvers = {
Query: {
modal: (_, { id }, { cache }) => {
console.log("get modal");
try {
const data = cache.readQuery({ query: modalStateQuery.getOne, variables: { id } });
console.log("data", data);
} catch (e) {
console.log("error", e);
}
return null;
},
modals: (_, { }, { cache }) => {
console.log("Modal List Resolver"); // this is never logged
}
}
}
const stateLink = withClientState({
cache,
resolvers,
defaults,
typeDefs
});
const link = ApolloLink.from([stateLink, httpLink]);
const client = new ApolloClient({
link,
cache,
dataIdFromObject: o => o.id
});
export default client;
-
// modal.query.js
import gql from "graphql-tag";
export const modalStateQuery = {
getOne: gql`
query ModalState($id: String!) {
modal(id: $id) #client {
id
open
}
}`,
getAll: gql`
query {
modals #client {
id
open
}
}
`
};
-
// modal.js
// ...
// fetching both for test purposes
export default compose(
graphql(modalStateQuery.getOne, { name: "modal" }),
graphql(modalStateQuery.getAll, { name: "allModals" })
)(Modal);
Ok, now the questions:
The number one problem I'm having is with the modal($id: id) query. When I execute modalStateQuery.getAll the modals resolver is never called, but I still get the list I defined in defaults in my component. But when I execute modalStateQuery.getOne I always get the same error:
error Error: Can't find field modal({"id":"login"}) on object (ROOT_QUERY) {
"modals": [
{
"type": "id",
"generated": false,
"id": "login",
"typename": "Modal"
},
{
"type": "id",
"generated": false,
"id": "signup",
"typename": "Modal"
}
]
}.
at readStoreResolver (readFromStore.js:71)
at executeField (graphql.js:90)
at graphql.js:46
at Array.forEach (<anonymous>)
at executeSelectionSet (graphql.js:40)
at graphql (graphql.js:35)
at diffQueryAgainstStore (readFromStore.js:124)
at readQueryFromStore (readFromStore.js:37)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.read (inMemoryCache.js:84)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery (inMemoryCache.js:181)
What is this array it is showing to me? Why isn't there all the props I defined in defaults (like open: false)? Could it be something wrong with the way I create my defaults?
In the apollo-cache-inmemory docs it doesn't define any resolvers, it just says that you should query your data just like you are doing it in the backend, passing the variables.
Also, why does modalStateQuery.getAll works even though the resolver is never called? What if I do want that resolver to be called (Maybe I want to check my backend first to check permissions or smth)?
Another curious behavior I noticed: When executing the modal resolver, the id variable is always correct, even though I didn't explicitly pass it as variable in my component, but the Modal.js component does have an id props that I pass to it:
return <Modal id="login"><LoginForm /></Modal>;
It makes me believe that apollo already recognizes that the Modal.js is being called with an id prop and automatically passes it to the query as a variable. Is that correct? It does it for any variable?
Thanks!

Relay Modern Mutations, RANGE_ADD / Append

I have a collection and a mutation to add a new item to it. I haven't been able to get Relay Modern to update the UI after a successful mutation.
I've got a PaginationContainer setup with the following query: prop
{
query: graphql`
fragment ContactsList_query on WPQuery {
id
contacts: posts(
first: $count,
after: $cursor
post_type: $postType,
order: $order,
category_name: $categoryName
) #connection(key: "ContactsList_contacts" ) {
edges {
node {
id
...ContactListItem_contact
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
`
},
That fetches correctly. I've then got a mutation to add a contact to this list.
Neither the config RANGE_ADD or the updater: callback techniques work at all.
I'm triggering this mutation like so
onSave = (fields) => {
insertPost(
fields.toJS(),
this.props.query.id,
this.props.relay.environment
);
}
No errors, just nothing updates.
const mutation = graphql`
mutation InsertPostMutation(
$data: InsertPostInput!
) {
insert_post(input: $data) {
wp_query {
id
}
postEdge {
node {
id
title
}
}
}
}
`;
export default function insertPost(data, id, environment) {
const variables = {
data,
};
commitMutation(
environment,
{
mutation,
variables,
onCompleted: (response, errors) => {
console.log('Response received from server.')
},
onError: err => console.error(err),
configs: [{
type: 'RANGE_ADD',
parentID: id,
connectionInfo: [{
key: 'ContactsList_contacts',
rangeBehavior: 'append',
}],
edgeName: 'postEdge'
}],
// updater: (store) => {
// // const inspector = new RecordSourceInspector(store)
// const payload = store.getRootField('insert_post')
// const newEdge = payload.getLinkedRecord('postEdge')
// const proxy = store.get(id)
// // Conn is always undefined here
// const conn = ConnectionHandler.getConnection(proxy, 'ContactsList_contacts')
// ConnectionHandler.insertEdgeAfter(conn, newEdge)
// }
},
);
}
Well, I was able to fix this by changing the line
#connection(key: "ContactsList_contacts")
To
#connection(key: "ContactsList_contacts", filters: [])
Seems it couldn't find the connection otherwise...
https://facebook.github.io/relay/docs/pagination-container.html#connection-directive
Then using the updater function the connection was found.

RepositoryNotFoundError : TypeORM

I am trying to get the following example working:
https://github.com/typeorm/javascript-example/tree/master/src/app3-es6
I am running into the following error:
Error
at new RepositoryNotFoundError (...\node_modules\typeorm\connection\error\RepositoryNotFoundError.js:24:23)
at Connection.findRepositoryAggregator (...\node_modules\typeorm\connection\Connection.js:513:19)
at Connection.getRepository (...\node_modules\typeorm\connection\Connection.js:405:21)
at ...\index.js:27:37
name: 'RepositoryNotFoundError',
message: 'No repository for "Post" was found. Looks like this entity is not registered in current "default" connection?'
here is index.js
const typeorm = require("typeorm"); // import * as typeorm from "typeorm";
const Post = require("./model/Post"); // import {Post} from "./model/Post";
// import Post from './model/Post.js';
const Category = require("./model/Category"); // import {Category} from "./model/Category";
typeorm.createConnection({
driver: {
type: "oracle",
host: "localhost",
port: 1521,
username: "uname",
password: "pwd",
sid: "dev"
},
entities: [
__dirname + "/entity/*.js"
],
autoSchemaSync: true
}).then(function (connection) {
console.log(connection);
let post = new Post.Post();
post.title = "Control flow based type analysis";
post.text = "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.";
post.categories = [new Category.Category(0, "TypeScript"), new Category.Category(0, "Programming")];
let postRepository = connection.getRepository(Post.Post);
postRepository.persist(post)
.then(function(savedPost) {
console.log("Post has been saved: ", savedPost);
console.log("Now lets load all posts: ");
return postRepository.find();
})
.then(function(allPosts) {
console.log("All posts: ", allPosts);
});
}).catch(function(error) {
console.log("Error: ", error);
});
Post.js in /model/
/*export */ class Post {
constructor(id, title, text, categories) {
this.id = id;
this.title = title;
this.text = text;
this.categories = categories;
}
}
module.exports = {
Post: Post
};
Category.js
/*export */ class Category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
module.exports = {
Category: Category
};
PostSchema.js in /entity/
const Post = require("../model/Post"); // import {Post} from "../model/Post";
const Category = require("../model/Category"); // import {Category} from "../model/Category";
const PostSchema = {
target: Post,
columns: {
id: {
primary: true,
type: "int",
generated: true
},
title: {
type: "string"
},
text: {
type: "text"
}
},
relations: {
categories: {
target: Category,
type: "many-to-many",
joinTable: true,
cascadeInsert: true
}
}
};
module.exports = {
PostSchema: PostSchema
};
CategorySchema.js
const Category = require("../model/Category"); // import {Category} from "../model/Category";
const CategorySchema = {
target: Category,
columns: {
id: {
primary: true,
type: "int",
generated: true
},
name: {
type: "string"
}
}
};
module.exports = {
CategorySchema: CategorySchema
};
i dont know what i am doing wrong
It looks like your entity import is not working. If you import via the wildcard:
entities: [
__dirname + "/entity/*.js"
],`
Make sure your model is compiled to js. You also could just import
createConnection({
...,
entities: [
Post,
...
],}).then(...)
For those who are using typescript and experience this problem: Be reminded that you need to include both ts and js file suffixes when specifying the entities-path:
ts used when locally running with ts-node
js used when having
built for production via tsc.
Code:
import * as path from 'path';
// ...
entities: [
// assuming _dirname is your project root
path.resolve(__dirname, '**/*.entity{.ts,.js}'),
],
I had the same problem for months and finally figured out what I was doing wrong.
When you import Entities, make sure the file names are EXACTLY matching. It's not going to throw any errors, but during the run time, it's going to throw the above error.
Ex. In the entity or model classes, if we import like this,
import { FooClass } from "./foo-Class.model";
it's different from
import { FooClass } from "./foo-class.model";
It won't show any errors, but when you try to call the table, it will show the exact same error.
I had the same problem. None of the solutions worked for me. After much debugging I figured out that you'll receive this error if your connection is closed.
So if you are facing this error, make sure your connection is not closed.
try {
connection = getConnection(config.name)
//after adding this if block, I no longer received this error
if (!connection.isConnected) {
await connection.connect();
}
} catch(err) {
connection = await createConnection(config);
}
If it is closed, connect it again.

How can I check if a connection has new items in Relay?

I have the following Relay container in my Feed component, that it is a simple list of Posts
export default Relay.createContainer(Feed, {
initialVariables: {
count: 5,
},
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
posts(first: $count) {
pageInfo {
hasNextPage
}
edges {
node {
id,
body
},
},
},
},
`,
},
});
Theses posts are organized by the most recent ones, how can I check if there are newer posts in my graphql server? I want to do a pulling strategy until I migrate it to graphql/relay subscriptions
Can I use forceFetch? I don't wanna to update Relay Store, I just wanna to notify the user that has new posts
One way I could think of is to have an endpoint which you supply with the latest timestamp. This endpoint returns for example the ids of the newer posts. On relay side you do a setTimeout(() => { this.props.relay.setVariables({timestamp: timestamp}); }, 60000)
and in the fragment something like:
const FooBar = Relay.createContainer(FooBarClass, {
initialVariables: {
timestamp: null
},
prepareVariables: vars => {
vars['timestampIsTruthy'] = !!vars['timestamp'];
return vars;
},
fragments: {
store: () => Relay.QL`
fragment on Query {
newerPosts(timestamp: $timestamp, first: 3) #include(if: $queryIsTruthy) {
totalCount
edges {
node {
id
}
}
}
}`,
},
});

Categories