If you do decide that it's worth the bundle size hit for using the Apollo, give Apollo Elements a try, it supports Vue quite well.
Live Demo of Apollo Elements in Vue
Some advantages over Fetch calls:
- declarative components
- cache normalized results
- if one query fetches user(id: 1) { id name picture }
, other queries can use that data without refetching
- local state management
- use components across frameworks
Open sourcing your cloud GraphQL database... bold move! After seeing your Graphcool admin console I'm sold, and this means I can run it locally now. Also on Product Hunt today: https://www.producthunt.com/posts/graphcool-framework Question: How do we sync schema changes between dev environment and production? As of right now, this just means we can see the well-designed Graphcool backend and don't have to worry about getting locked into a cloud offering, but it needs schema migrations to use in dev environments.
It seems like Realm is also an option now: https://realm.io/blog/realm-scales-to-the-web/
Realm is pretty awesome for mobile apps, so if they can transfer any of that magic to GraphQL it would definitely be something to look out for.
Hi, iam using express-graphql server on GraphQL end and I have added nginx config file as well as how we are using socket below, it is not complete code and hope it helps
Good question.
Sqlmancer is similar to Prisma, in that it generates a type-safe database client for you that can then be used inside your resolvers. Prisma requires you to define your database models separately from your schema, while Sqlmancer relies directly on your type definitions.
Prisma 2 no longer supports schema delegation or GraphQL binding, so you can't just pass along your query and have it automagically work with the client. Sqlmancer allows you to pass in the GraphQLResolveInfo object passed to your resolver and it uses that to build the SQL query. Maybe u/nikolasburk can correct me here, but as I understand it, the only way to do bind your schema to your Prisma models like that is to use Nexus and its Prisma plugin.
Prisma 2 interacts with the database through its own query engine binary. Sqlmancer, on the other hand, relies on existing driver libraries like pg
and mysql2
. As a result, Sqlmancer is a bit less restrictive in what it can do. For example, it supports long-running transactions, which Prisma doesn't.
Since Hasura is not a library but more of an out-of-the-box solution, it's a bit harder to compare the two. In terms of querying capabilities, once Sqlmancer supports aggregate queries, it should be somewhat more robust than Hasura (for example, it already supports filtering and sorting by a relation's aggregated values). Hasura also currently only works with Postgres, while Sqlmancer will minimally support MariaDB and MySql as well by the time it hits beta.
These comparisons are based on my only rough familiarity with the two solutions. My apologies to both Hasura's and Prisma's teams if I misrepresented anything in the comments above.
I will suggest you to use Prisma, that will simplify things for you. You will not have to handle schema part of the SQL/NoSQL DB that you intend to use, prisma itself takes care of that.
The equivalent for the above SQL table in prisma would be something like:
​
type Ticket {
id: ID! @unique @id
status: Integer!
}
​
type Event {
id: ID! @unique @id
ticket: Ticket! @relation(link: INLINE)
status: Integer!
}
​
@unique
suggests that it has to be unique
@id
makes it primary key identity
!
makes it not null
well, prisma deploy will generate the client (bindings) but to get the auto generated schema (.graphql file) for the service you need to run this:
​
graphql get-schema --endpoint $PRISMA_ENDPOINT --output prisma.graphql --no-all
​
It's all laid out in the docs: https://www.prisma.io/docs/data-model-and-migrations/data-model-knul/
Yeah I'll have to check it out. I only just recently discovered that postgraphile isn't the only one, only one I've tried so far though. Also came across https://www.prisma.io/ - not sure how it differs from the other two.
Cool to see that this way of doing things is gaining some traction overall.
I've even started to wonder if it makes sense to just use graphql to query my databases from the backend too. i.e. Instead of using a regular SQL ORM.
I guess it would be slower, but wondering if there's other disadvantages.
I guess it would need a graphql client that can hydrate your models.
I'm using TypeORM for my normal DB queries on the backend, I think either way, I'll still add a saveViaGraphql() method to my base model class so that I can use my regular models on the backend and communicate with remote DBs without opening ports or needing VPN etc. That was the initial thought that got me wondering if it makes sense to just use graphql for everything. I'm sure there would be some downsides though.
Looking into it made me even more confused about the whole thing for a while. You are right. For anybody else there is some good info here about the differences between the two.
Your situation is super common - and the prime use case for GraphQL Bindings. Basically you are using bindings to connect to an existing GraphQL API and reuse it to define a new GraphQL API.
Here's a simple example. Let's say you only want to expose a feed
field that exposes all published posts. Then you can use the posts
query exposed by the Prisma Binding like so:
feed(parent, args, ctx, info) { return ctx.db.query.posts({ where: { isPublished: true } }, info) },
In this code snippet, ctx.db
relates to the Prisma Binding, and with ctx.db.query.posts
we can access the posts
query.
Now you can easily add authentication logic. Let's say only logged-in users can see the feed - so let's add a check before returning the feed!
feed(parent, args, ctx, info) { if (!isAuthenticated(ctx)) { throw new Error('Not authenticated!') }
return ctx.db.query.posts({ where: { isPublished: true } }, info) },
You can find a complete example for this entire setup here.
Also looking at the JWT code, I would suggest limiting the algorithms that can de used to decode/encode explicitly.
I believe the golang libraries are safe but we have seen confusion attacks in the past: https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
You can create a login mutation, passing in username and password and returning jwt token, and then attach that token to consequent graphql calls, in line with https://strapi.io/blog/a-beginners-guide-to-authentication-and-authorization-in-strapi
I see what you mean, the problem of having the tables prefixed by schema rather than the schemas being a root-level field in the graph.
What you would probably ideally like to have happen, is that new schemas be created as root-level fields, so that you can query something like this:
query {
primary {
user {
email
}
}
secondary {
user {
email
}
}
}
Instead what you get is:
query {
primary_user {
email
}
secondary_user {
email
}
}
We are aware of this, considerable thought has to go into the proper implementation.
So what can you do?
The easiest option may be to use a middleware function that takes GraphQL query strings, and manipulates the AST's to namespace the top-level selection sets based on the current user's schema name.
I've written an example implementation here: https://repl.it/@GavinRay97/BeautifulComposedPerl
It's not ideal, but perhaps it could suffice until we implement our longer-term strategy for dealing with multi-tenant schema permissions?
Subscriptions aren’t tied to WebSockets, you can use any transport such as HTTP. Socket.io is a hybrid which can do both WebSocket and HTTP. You can even do GraphQL over Socket.io. I actually built a convenience wrapper for easily doing GraphQL over Socket.it 😄 https://github.com/n1ru4l/graphql-live-query/tree/main/packages/socket-io-graphql-server
If you want to reduce GraphQL payload overhead look into persisted GraphQL operations (search term: "persisted queries").
As you said for most smaller applications all those things would be over kill.
I haven't used Firebase much for anything outside of auth so I can't really chime in too much on the pros/cons but it seems like it's definitely doable. My understanding of Firebase is that the goal is to basically avoid needing to have your own API (entirely?) ? I don't know much about it and was never a fan so never got too far with it =X
Check this out though: https://firebase.google.com/docs/storage/web/start
Are you just looking to store images? or some other file types?
You can use the built-in __Type
type, which is normally used for introspection. A field that has the type __Type
can return any GraphQLType
in its resolver. It can then be queried just like this:
{
myType {
name
description
fields {
name
type {
name
}
}
}
}
Check out this sandbox for a complete example.
While the projects listed in the other comments include similar implementation, I finally found a tutorial that covers exactly what I was looking for with steps to achieve OAuth via GraphQL - How to nail social authentication in GraphQL.
Essentially, the steps are as follows.
Your reply said “unpredictable”. So I’m guessing you meant “predictable”.
I recall reading somewhere that they were not, particularly with an async implementation. But maybe that was just with nested mutations?
Update: It was nested mutations. See the following article.
https://www.freecodecamp.org/news/beware-of-graphql-nested-mutations-9cdb84e062b5/
Implementing a GraphQL layer yourself on top of a database can be good for learning. However it means you will be writing a lot of code for just simple crud apis.
Also in that case you will need to implement all the optimizations like data loader pattern yourself otherwise your graphql API can become a bit costly for production workloads.
I recommend you use something like Space Cloud so that you don't have to implement the API layer and database yourself. It will autogenerate APIs for your databases. Since it let's you to configure the security rules for your database, you can directly consume the auto generated APIs from frontend. Join our discord server if you need any help around it - https://discord.com/invite/RkGjW93
Ah! Thanks for answering. Just to clarify, I'm trying to find an estimate of how widespread use of GraphQL is, and how many times GraphQL is used to perform a query through the web every day around the world. I just went to prometheus.io and it appears to be a way to actually measure queries, but I'm not trying to actually measure every GraphQL query every day...rather I'm just looking for estimates because I don't even know which websites/applications use GraphQL to pull data from places. Does that make more sense? Would you happen to have an estimate of the number of queries that are run through websites around the world every day? Or is this number unobtainable?
I am using Cloudinary to upload and store images. The URL for uploaded images is stored in my backend via graphql. It has taken a lot of the complexity away from uploading and storing images.
Thanks for reading the article.
We haven't done any specific benchmarking on multiple cloud providers, but we started with Dedicated servers then quickly moved to Google Cloud Kubernetes. The difference was significantly bad :/ but in the scope of this article (Graphql Subscriptions), our main load is coming on Nginx containers/pods because that's the single point of keeping connections alive and transferring all the data across the infrastructure.
Based on our experience, our single Node.js GraphQL API container/pod can handle around 10K live connections with 1 Core CPU and about 4GB of Ram, which is in avg about 300Kb - 400Kb per single WebSocket connection. Ideally, you will have a lot less per connection if you have fewer connections, but because of Node.js GC, in most of the cases, intensive network IO is not allowing to clean up memory very often.
So we ended up having 6 instances for our Kubernetes cluster (scaling up if needed) with 4 Core CPU and 50Gb of memory. You probably will say that 4 CPU is a way to low, BUT it turns out that keeping CPU resources with an automatic Kubernetes configuration freed up our energy to think about how many CPU cores we need, if we are getting an alert that CPU load is too high, we just putting another instance.
Costs are about 3K to 5K per month, based on our load. BUT most likely we will move out of the cloud next year, because having 10X more resources on dedicated servers (rented) is just about 2K-3K a month, and performance is way better. From our experience, Google cloud feels like a very slow on CPU based tasks, we were getting more out of our dedicated server CPU core than Google cloud ones.
Anyway, we still optimizing stuff, because based on the nature of our product hexometer.com we have a lot of CPU and Network-intensive operations.
I've tried Google Cloud and found it extremely confusing, especially App Engine. It's poorly documented and deploying an app can take more than 30 minutes for reasons I don't know. I also couldn't figure out the exact pricing and the steps to using your own domain name didn't work. I spent a lot of time on it and eventually gave up. Next I tried Heroku and found it to be much easier to understand and use. Scalingo is an alternative to Heroku, cheaper but they don't nearly have as many add-ons as Heroku.
> NoSQL databases lack the neatness of relations but aren't they more performant?
Performance is hard to generalize and really depends on the way the data is modelled and query patterns.
Based on this benchmark: https://www.arangodb.com/2018/02/nosql-performance-benchmark-2018-mongodb-postgresql-orientdb-neo4j-arangodb/ It looks like MongoDB isn't necessarily more performant.
The one thing that is easier with MongoDB is setting up replication. However, with PostgreSQL there are many hosted solutions (AWS RDS, Google Cloud SQL, Heroku, and many more) that provide you with a replica and automated backups.
I wouldn't spend the extra effort with using JWT for session tokens. There's a few reasons why JWTs are not suited for authentication:
Instead of JWT, consider using plain-old opaque session tokens. They are much more secure since they don't leak any information about the user, since they are random bytes. They are validated by simple comparison, leaving out a huge possibility of vulnerabilities. And they are also much more scalable, since they can be generated to a fixed size, making it optimal to store in your database (whereas JWTs requires dynamic allocation).
As a toy project, JWTs are fun to work with, but for more serious projects I don't recommend anyone to use JWTs because of the many pitfalls it has. They are great for internal use, such as having multiple services which require some information about a request over the network and are meant to be short-lived for this purpose.
Hope this helps :)
Hey! I'm from Hasura. I think this is the same post that was originally at auth0 https://auth0.com/blog/using-jwts-for-graphql-authorization-with-hasura/ Someone seems to have copied the content and put it up elsewhere. :(
This is not a post we wrote and we don't certainly don't generate them.
​
On the technical side, we implement auth by having a postgres RLS like system in the API layer. This authz system allows you to refer to session variables from the JWT and enforce them when the SQL queries for GraphQL are generated.
I tend to separate my GraphQL from authentication - calls to my GraphQL server without a JWT just don't go through.
Auth0 have a pretty good example on how this can be done here: https://auth0.com/blog/develop-modern-apps-with-react-graphql-apollo-and-add-authentication/
(I realise this sounds like a massive plug for Auth0, but they're probably the easiest Auth provider to work with)
We’ve considered AppSync at work, but ultimately decided to go for Apollo Server for ease of development, testing, deployment, etc. Team mate of mine did a pretty comprehensive write-up: https://dev.to/raoulmeyer/appsync-basically-graphql-as-a-service-3bp1
I'm using it fine under emacs and VSCode, maybe it's an issue with your setup?
> Then, again, nobody on the net knows when to use interface and when to use type, it's a mess.
There are some things you can do with types, which you can't with interfaces and vice versa. If you got a string union type, you can use a type to restrict the keys of an object
Interfaces are generally better at inheritance, types at compositional patterns. There are a few differences and there are good places to find which.
It wasn't really clear to me in the beginning, either, but the more you work with them, the more you find suitable applications for them. I personally tend to use types instead of interfaces, because I feel they are more universally applicable for my problems.
Glancing at the docs, it doesn't look like you can use this option if your events are provided through a GraphQL endpoint. But it looks like you can also provide a function for fetching the events. So just use that:
const calendar = new Calendar(calendarEl, {
...
events: async function(info, successCallback, failureCallback) {
const { startStr, endStr } = info
const query = `...`
const variables = {...}
try {
const res = await fetch('YOUR_ENDPOINT_URL', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
})
const { data, errors } = await res.json()
// Parse data for your events and call successCallback with them
} catch (e) {
failureCallback(e)
}
},
}
Can I ask you what is wrong with this?
I am able to sucessfully run the query (delete audience group) but neither attempt at updating the cache works.
I am not able to put a break-point or console log and the console gives me no warnings or errors. This kind of black-box programming is making me pull my hair out.
BTW, the article you linked was pretty clear but it still doesn't work for me.
Prisma does provide some of its own mitigations for the n+1 problem: https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance
The info arg will hold anything that has been passed to the query, so if you query on the parent with a customer number, then the child can use what is in the info arg in the resolver.
Give this article a look over. Its all about understanding when and how to use the info arghttps://www.prisma.io/blog/graphql-server-basics-demystifying-the-info-argument-in-graphql-resolvers-6f26249f613a
That file comes form a toolkit called Prisma:
https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-schema/prisma-schema-file
If you plan to use Prisma then it seems you should not rename that file.
Thanks for the shouout! We're definitely putting a lot of effort into making all database queries entirely type safe (even partial queries). You can see an example of this in this demo video.
That’s all very nice and I am sure you did an awesome job there, but what pushes you to use PHP over JS/TS or Go?
Code first is indeed more appealing than schema first and other projects like Prisma followed the same path.
I am far from being a GraphQL expert but I personally feel Apollo server is a master piece.
Thanks a lot, that makes a lot of sense to me! I'll quickly follow up on your points individually as well :)
> Our dB types weren’t consistent and meant we couldn’t leverage a data lake for reporting
I completely understand that this can be a major blocker! As I mentioned before, the only "workaround" right now would be to only use Prisma's auto-generated DB client and not (yet!) its migration system. Native DB type support is coming really soon to the migrations as well though!
> Lack of Federation support
I'm assuming you're referring to "Apollo Federation" here? In that case, it's not quite accurate that Prisma "doesn't support" it. You can certainly implement the resolvers of a federated schema using. In that case, you'd use Prisma's auto-generated DB client to talk to your DB inside the resolver.
> Prisma 2 introduces a variant of Graphql, I believe. We wanted to stick to the standardised version. I could be mistaken in this however as I haven’t done a lot of research into this
I'd love to learn more about what gave you the impression that Prisma 2 introduces a variant of GraphQL! Did you get that impression from the docs or some blog post? Could you point me to that?
Note that Prisma 2 itself is a database toolkit, you can use it to implement any sort of application that uses a database, like a REST API, a gRPC API, or of course a GraphQL API (if it talks to a database).
Aside from building out Prisma, we're also heavily investing into GraphQL Nexus, a [code-first])(https://www.prisma.io/blog/the-problems-of-schema-first-graphql-development-x1mn4cb0tyl3) GraphQL schema construction library. We're also building a "Prisma-plugin" for Nexus, so that you can easily connect your Nexus resolvers to your DB. This gives you a single source of truth for your types and saves tons of boilerplate that would be otherwise needed for the resolvers!
Spring Boot is based on the JVM while Apollo is a NodeJS platform.
As other people suggested, you don’t have to “choose” between them in the sense that they can be used within the same project. However they do need to run on two different micro-services since they use a completely different runtime.
Using Apollo totally makes sense as it eliminates a lot of boilerplate code and lets us focus on designing our API. Tools like Prisma can even automate the API generation.
That said, unless you really are tied to Spring Boot, I recommend switching to a pure NodeJS backend. When it comes to Graphql, you’ll be far better served in the TypeScript/JavaScript ecosystem than in the Java world.
By the way, I think we might know each other in real life. Does my name ring a bell?
There is a good write up on the Prisma website, which appears to detail loosely what is being asked.
Implementation #3 may assist.
I note though, it’s a lot of effort for something that can be easily handled on the client, or if it is used frequently, add it to the schema and create it programmatically by joining the two fields (first and last name) in the resolver (manage programmatically on create and update of user, so change to either first or last name is reflected in fullName).
I just quickly want to follow up with two comments:
We had an awesome experience rebuilding HyreCar's infrastructure with Prisma as a key component. They actually wrote a case study about it on their blog!
We just officially announced it :)
​
https://www.prisma.io/blog/using-graphql-nexus-with-a-database-pmyl3660ncst/
> There really ought to be an ORM that lets you expose your models as a GraphQL API easily.
This is exactly what we are currently working on with the nexus-prisma
plugin (disclaimer: I work at Prisma) . You'll be able to just expose CRUD and other operations for Prisma models in your GraphQL API without writing any resolvers for them.
You first define your Prisma models in SDL:
type User {
id: ID! @unique
email: String! @unique
}
Then to expose CRUD operations for User
(and other types), you can configure your GraphQL schema + server like this:
const Query = prismaObjectType({ name: 'Query' })
const Mutation = prismaObjectType({ name: 'Mutation' })
const schema = makePrismaSchema({
types: [Query, Mutation],
// ... some more config stuff
})
const server = new GraphQLServer({
schema,
})
You can also easily customize the operations that are exposed.
There's a blog post about this topic coming later this week. If you want to get a sneak peek, you can check out the TS GraphQL examples already (note that there still might be some changes over the next few days).
Thanks for sharing your thoughts! I think we can agree to disagree here :) As I said, we have many customers using Prisma happily in production (you can find some customer stories on our blog). Granted that Prisma isn't perfect, but it does make developers a lot more productive by creating an easier mental model for working with databases and enabling type-safe database access. It might have some flaws (show me a tool that doesn't), but we do have excellent engineers and overall a great team/company setup that I think many of the issues you might have encountered will be ironed out soon or have appropriate workarounds.
Hi, I'm the author of the article and definitely want to acknowledge that you can be productive with SDL-first. The folks at 99designs have done a great job with their gqlgen
library (it actually was a huge inspiration for us when we built <code>graphqlgen</code>).
As mentioned in the article, most of the problem areas apply to the JavaScript ecosystem. Plus, we've also said that SDL-first can work well, but only by using additional tools (e.g. if you weren't using the codegen library, you'd have a much harder time). So, the idea is not to condemn SDL-first per se, but rather to raise awareness for its problem areas and the fact that solving these problems requires the overhead of learning additional tools (often also new mental models) that developers need to integrate into their workflows.
I also want to note that codegen doesn't solve all problems, but particularly the problem area of keeping SDL-definitions and resolver implementations in sync. I'd be curious to hear more about your experience, e.g. how large your GraphQL schema is? In larger schemas, you typically enter the problem areas of modularization and code redundancy as well.
There is a lesser-known feature I've used in Prisma which lets you configure triggers by using subscriptions. Here's is a link to their docs where this feature is used.
If you aren't picky about the database and don't even mind managing the database itself with graphql, you could look at Prisma which is an interesting ORM-like graphQL-based tool.
Running prisma deploy will also run prisma generate so you don’t need to explicitly generate every time. I believe the issue is that your prisma.yml file is missing a few lines that tell it what to generate and where to put it. It should look something like:
generate: - generator: javascript-client output: ./prisma-client/
See docs here https://www.prisma.io/docs/1.17/prisma-client/setup/generating-the-client-rsc1/
No, by migration I mean altering db schema thru code and tracking them in all environment (e.g. dev, stage, production). It's popular concept in Java, Python and Rails world. Knex also support it. Prisma has document about migration, but nothing in details.
Hi Tom – Johannes from Prisma/Graphcool here!
Sorry to hear about your inconveniences – we're hard at work to keep up with the fast user growth and load of their applications. We'll soon roll out some updates to our server infrastructure which will make it a lot more resilient.
Regarding your question about Prisma vs Graphcool. The TLDR is that Graphcool is a great way to get started with Graphcool and a great fit for simple applications. For more advanced use cases Prisma is definitely the right fit as it fits seamlessly into other libraries/tools and gives you the entire flexibility & power of GraphQL. I recommend checking out this post in our forum for more information: https://www.prisma.io/forum/t/graphcool-framework-and-prisma/2237
Please let me know if you have any other questions! Happy to help!