crystal
🔮 Graphile's Crystal Monorepo; home to Grafast, PostGraphile, pg-introspection, pg-sql2 and much more!
Top Related Projects
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
A reference implementation of GraphQL for JavaScript
The flexible backend for all your projects 🐰 Turn your DB into a headless CMS, admin panels, or apps with a custom UI, instant APIs, auth & more.
Quick Overview
Crystal is a powerful GraphQL client for TypeScript and JavaScript, designed to work seamlessly with Apollo Server. It provides type-safe GraphQL operations and results, automatic code generation, and excellent developer experience with features like autocomplete and inline documentation.
Pros
- Type-safe GraphQL operations and results
- Automatic code generation from GraphQL schema
- Excellent developer experience with autocomplete and inline documentation
- Seamless integration with Apollo Server
Cons
- Limited to TypeScript and JavaScript ecosystems
- Requires additional setup and configuration compared to simpler GraphQL clients
- Learning curve for developers new to GraphQL or type-safe programming
- May have performance overhead for very large schemas or complex queries
Code Examples
- Defining a GraphQL query:
const GET_USER = crystal.query({
user: [
{ id: crystal.arg.string.required() },
{
id: true,
name: true,
email: true,
},
],
});
- Executing a query and accessing typed results:
const result = await crystal.execute(GET_USER, { id: "123" });
console.log(result.user.name); // TypeScript knows this is a string
- Using fragments for reusable query parts:
const UserFragment = crystal.fragment({
user: {
id: true,
name: true,
email: true,
},
});
const GET_USER_WITH_FRAGMENT = crystal.query({
user: [
{ id: crystal.arg.string.required() },
{
...UserFragment,
},
],
});
Getting Started
- Install Crystal:
npm install @graphile/crystal
- Generate types from your GraphQL schema:
npx crystal-codegen --schema path/to/schema.graphql --output src/generated/crystal.ts
- Import and use Crystal in your code:
import { crystal } from './generated/crystal';
const GET_USER = crystal.query({
user: [
{ id: crystal.arg.string.required() },
{
id: true,
name: true,
email: true,
},
],
});
async function fetchUser(id: string) {
const result = await crystal.execute(GET_USER, { id });
return result.user;
}
Competitor Comparisons
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Pros of Prisma
- More extensive ecosystem with broader language support (TypeScript, JavaScript, Go)
- Larger community and more frequent updates
- Advanced features like migrations and introspection
Cons of Prisma
- Steeper learning curve for beginners
- Requires a separate schema file, which can add complexity
- More opinionated, potentially limiting flexibility in some cases
Code Comparison
Prisma:
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@example.com',
},
})
Crystal:
user = User.create(name: "Alice", email: "alice@example.com")
Key Differences
- Prisma uses a declarative schema approach, while Crystal relies on traditional ORM patterns
- Prisma offers type-safe database access, which is particularly beneficial in TypeScript projects
- Crystal provides a more lightweight and Ruby-like syntax, which may be preferable for Ruby developers
Use Cases
- Prisma: Ideal for large-scale applications with complex data models and TypeScript/JavaScript ecosystems
- Crystal: Well-suited for Ruby developers looking for a familiar syntax and simpler setup in smaller to medium-sized projects
Community and Support
Prisma has a larger and more active community, resulting in more resources, tutorials, and third-party integrations. Crystal, being newer and more niche, has a smaller but growing community focused on Ruby-like simplicity.
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
Pros of GraphQL Engine
- More comprehensive and feature-rich, offering real-time subscriptions and event triggers
- Supports multiple databases, including PostgreSQL, MySQL, and SQL Server
- Provides a user-friendly web interface for schema management and API exploration
Cons of GraphQL Engine
- Heavier and more complex setup compared to Crystal's lightweight approach
- May have a steeper learning curve for beginners due to its extensive feature set
- Requires more system resources to run efficiently
Code Comparison
GraphQL Engine (Hasura):
type Query {
users(limit: Int, offset: Int): [User!]!
}
type User {
id: Int!
name: String!
email: String!
}
Crystal:
class Query < GraphQL::Schema::Object
field :users, [User], null: false do
argument :limit, Integer, required: false
argument :offset, Integer, required: false
end
end
class User < GraphQL::Schema::Object
field :id, ID, null: false
field :name, String, null: false
field :email, String, null: false
end
Both projects aim to simplify GraphQL API development, but GraphQL Engine offers a more comprehensive solution with additional features and database support. Crystal, on the other hand, provides a lightweight and flexible approach that may be more suitable for smaller projects or those requiring custom implementations. The code comparison shows that GraphQL Engine uses a declarative schema definition, while Crystal employs a programmatic approach using Ruby.
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
Pros of Supabase
- More comprehensive platform with built-in authentication, storage, and real-time features
- Larger community and ecosystem, with extensive documentation and tutorials
- Offers a user-friendly dashboard for database management and API exploration
Cons of Supabase
- Less flexible for custom GraphQL schema design compared to Crystal
- May have a steeper learning curve for developers familiar with traditional PostgreSQL setups
- Potential vendor lock-in due to its all-in-one nature
Code Comparison
Crystal:
type Query {
users: [User!]!
}
type User {
id: ID!
name: String!
}
Supabase:
CREATE TABLE users (
id UUID DEFAULT uuid_generate_v4(),
name TEXT NOT NULL
);
Both projects aim to simplify database operations, but they take different approaches. Crystal focuses on GraphQL schema generation from PostgreSQL, while Supabase provides a full-stack development platform with additional features beyond just database access. The choice between them depends on specific project requirements and developer preferences.
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
Pros of Apollo Server
- Extensive ecosystem and community support
- Built-in features like caching, subscriptions, and file uploads
- Seamless integration with Apollo Client for full-stack GraphQL development
Cons of Apollo Server
- Steeper learning curve for beginners
- Potentially more complex setup for simple use cases
- Heavier footprint compared to lightweight alternatives
Code Comparison
Apollo Server:
const { ApolloServer } = require('apollo-server');
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
Crystal:
require "graphql"
schema = GraphQL::Schema.new(
query: GraphQL::ObjectType.new(
name: "Query",
fields: {
hello: GraphQL::Field.new { "Hello world!" }
}
)
)
While Apollo Server provides a more feature-rich and widely adopted solution, Crystal offers a lightweight and performant alternative for GraphQL development. Apollo Server excels in complex applications with its extensive tooling and integrations, whereas Crystal may be more suitable for simpler projects or those prioritizing performance. The code comparison highlights the different approaches, with Apollo Server using a JavaScript-based setup and Crystal utilizing a Ruby-like syntax.
A reference implementation of GraphQL for JavaScript
Pros of graphql-js
- Mature and widely adopted implementation of GraphQL for JavaScript
- Extensive documentation and community support
- Flexible and can be used with various JavaScript frameworks and environments
Cons of graphql-js
- Larger bundle size compared to Crystal
- Potentially slower performance due to JavaScript's interpreted nature
- Requires more boilerplate code for setup and configuration
Code Comparison
graphql-js:
const { graphql, buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const rootValue = { hello: () => 'Hello world!' };
graphql({ schema, source: '{ hello }', rootValue }).then((response) => {
console.log(response);
});
Crystal:
require "graphql"
schema = GraphQL::Schema.new(
query: GraphQL::ObjectType.new(
name: "Query",
fields: {
"hello" => GraphQL::Field.new { "Hello world!" }
}
)
)
result = schema.execute("{ hello }")
puts result
Both implementations achieve similar functionality, but Crystal's syntax is more concise and type-safe. However, graphql-js offers more flexibility and ecosystem support, making it suitable for a wider range of projects and use cases.
The flexible backend for all your projects 🐰 Turn your DB into a headless CMS, admin panels, or apps with a custom UI, instant APIs, auth & more.
Pros of Directus
- More comprehensive headless CMS solution with a user-friendly admin interface
- Supports multiple database types, including PostgreSQL, MySQL, and SQLite
- Active development with frequent updates and a larger community
Cons of Directus
- Heavier and more complex system, potentially overkill for simpler projects
- Steeper learning curve due to its extensive feature set
- May require more server resources to run efficiently
Code Comparison
Crystal:
type Query {
users: [User!]!
}
type User {
id: ID!
name: String!
email: String!
}
Directus:
{
"collections": {
"users": {
"fields": {
"id": { "type": "integer", "primary": true },
"name": { "type": "string" },
"email": { "type": "string" }
}
}
}
}
Summary
Crystal is a lightweight GraphQL framework focused on PostgreSQL databases, while Directus is a full-featured headless CMS supporting multiple database types. Crystal offers simplicity and performance for GraphQL-specific projects, whereas Directus provides a more comprehensive solution for content management with a user-friendly interface. The choice between the two depends on project requirements, database preferences, and the desired level of complexity.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð® Graphile's Crystal Monorepo
At Graphile we love GraphQL so much we named ourself for our love of it! This repository houses many of the Graphile packages that relate to GraphQL (or relate to the packages that relate to GraphQL, or relate to those package...); the two headline projects are Grafast and PostGraphile but there's many other packages, a fair few of which can be used independently - see below for more details.
Grafast: A cutting-edge planning and execution engine for
GraphQL.js â use this as a drop-in replacement for the execute
method from
GraphQL.js and by moving from traditional resolvers to Grafast "plan
resolvers" you'll be able to leverage the declarative nature of GraphQL requests
to execute your business logic in the most efficient way, leading to reduced
server load and happier customers. Use this if you're building your own GraphQL
schemas and want the best performance and efficiency without having to put much
extra effort in.
PostGraphile: An incredibly low-effort way to build a well structured and high-performance GraphQL API backed primarily by a PostgreSQL database. Our main focusses are performance, automatic best-practices and customisability/extensibility. Use this if you have a PostgreSQL database and you want to use it as the "source of truth" for an auto-generated GraphQL API (which you can still make significant changes to). NOTE: thanks to graphile-export you can also use this as a starting point for an API that you then manage yourself.
â¡ï¸ For PostGraphile V4 see the legacy branch |
---|
Project summaries
Here's a rough breakdown of the main packages:
- grafast - standalone cutting-edge planning and execution engine for
GraphQL; see above for full description.
- @dataplan/pg - plan classes for interacting with PostgreSQL
- @dataplan/json - plan classes for encoding/decoding JSON
- graphile-export - a package that can (under the right circumstances)
export an in-memory dynamically-constructed GraphQL schema to raw JavaScript
source code that can be imported and executed
- eslint-plugin-graphile-export - an ESLint plugin that helps you write code compatible with graphile-export
- jest-serializer-graphql-schema - a simple Jest serializer that
understands GraphQL schemas and thus does not fill snapshots with
\"\"\"
etc. - graphile-config - a module that handles the plugins, presets and configuration files for Graphile software - a universal configuration layer.
- graphile-build - a system for building a GraphQL.js schema from
"plugins", particularly useful for auto-generated GraphQL APIs (e.g.
PostGraphile uses this) but also useful for hand-rolled schemas that have a
lot of modular but widely-used concerns such as connections, naming, etc.
- graphile-build-pg - plugins for
graphile-build
that understand@dataplan/pg
(i.e. PostgreSQL) services and can generate types, relations, mutations, etc for these database resources.
- graphile-build-pg - plugins for
- @graphile/lru - an obsessively performant least-recently-used cache
(possibly the fastest general purpose LRU cache in Node.js) with a
ridiculously tiny feature set; you almost certainly want @isaacs'
lru-cache
instead of this. - pg-sql2 - a library for building highly dynamic SQL-injection-proof PostgreSQL queries using tagged template literals.
- pg-introspection - a strongly typed introspection library for PostgreSQL, generated from the PostgreSQL documentation to provide up-to-date details of each introspection field.
- postgraphile - pulls most of the above technologies together; see above for full description.
Crowd-funded open-source software
To help us develop this software sustainably, we ask all individuals and businesses that use it to help support its ongoing maintenance and development via sponsorship.
Click here to find out more about sponsors and sponsorship.
And please give some love to our featured sponsors ð¤©:
The Guild * |
Dovetail * |
Stellate * |
Steelhead * |
* Sponsors the entire Graphile suite
Why the "crystal" monorepo?
Originally what is now Grafast (and was previously DataPlanner) was known by the codename "Graphile Crystal." This lead us to use the ð® emoji to represent the project in secret before we announced it publicly, as a codeword for those in the know. Now that Grafast is the name for our planning and execution engine and we needed a name for the monorepo that wasn't too GraphQL specific (since there are things in here that aren't strictly related to GraphQL) and we figured that calling it the Crystal monorepo would honour our original nickname for the project. Rumours that the name was inspired by the maintainers' crystal wedding anniversary are greatly exaggerated.
Top Related Projects
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.
The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
🌍 Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
A reference implementation of GraphQL for JavaScript
The flexible backend for all your projects 🐰 Turn your DB into a headless CMS, admin panels, or apps with a custom UI, instant APIs, auth & more.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot