npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

Iā€™ve always been into building performant and accessible sites, but lately Iā€™ve been taking it extremely seriously. So much so that Iā€™ve been building a tool to help me optimize and monitor the sites that I build to make sure that Iā€™m making an attempt to offer the best experience to those who visit them. If youā€™re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, šŸ‘‹, Iā€™m Ryan HefnerĀ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If youā€™re interested in other things Iā€™m working on, follow me on Twitter or check out the open source projects Iā€™ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soonā€“ish.

Open Software & Tools

This site wouldnā€™t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you šŸ™

Ā© 2024 ā€“Ā Pkg Stats / Ryan Hefner

@foodfresh/postgraphql

v4.0.0-alpha2.23

Published

A GraphQL schema created by reflection over a PostgreSQL schema šŸ˜

Downloads

5

Readme

PostGraphQL@next

Package on npm Gitter chat room Donate

This is the ALPHA VERSION of PostGraphQL v4; use with caution and monitor #506!

A GraphQL schema created by reflection over a PostgreSQL schema.

The strongly typed GraphQL data querying language is a revolutionary new way to interact with your server. Similar to how JSON very quickly overtook XML, GraphQL will likely take over REST. Why? Because GraphQL allows us to express our data in the exact same way we think about it.

The PostgreSQL database is the self acclaimed ā€œworldā€™s most advanced open source databaseā€ and even after 20 years that still rings true. PostgreSQL is the most feature rich SQL database available and provides an excellent public reflection API giving its users a lot of power over their data. And despite being 20 years old, the database still has frequent releases.

With PostGraphQL, you can access the power of PostgreSQL through a well designed GraphQL server. PostGraphQL uses PostgreSQL reflection APIs to automatically detect primary keys, relationships, types, comments, and more providing a GraphQL server that is highly intelligent about your data.

PostGraphQL holds a fundamental belief that a well designed database schema should be all you need to serve well thought out APIs. PostgreSQL already has amazing user management and relationship infrastructure, why duplicate that logic in a custom API? PostGraphQL is likely to provide a more performant and standards compliant GraphQL API then any created in house. Focus on your product and let PostGraphQL manage how the data gets to the product.

For a critical evaluation of PostGraphQL to determine if it fits in your tech stack, read evaluating PostGraphQL for your project.

Introduction

Watch a talk by the original author at GraphQL summit for a fast 7 minute introduction to using the PostGraphQL project. This was using v2; we're now up to v4 which has many more bells and whistles!

PostGraphQL at GraphQL Summit

Usage

First install using npm:

npm install -g postgraphql@next

ā€¦and then just run it! By default, PostGraphQL will connect to your local database at postgres://localhost:5432 and introspect the public schema.

postgraphql

For information about how to change these defaults, just run:

postgraphql --help

You can also use PostGraphQL as native HTTP, Connect, Express, or Koa middleware. Just import postgraphql:

import { createServer } from 'http'
import postgraphql from 'postgraphql'

createServer(postgraphql())

For more information around using PostGraphQL as a library, and the options the API expects read the library usage article.

There is also a docker image for running PostGraphQL maintained by @angelosarto, simply pass the same options to the docker container:

docker pull postgraphql/postgraphql
docker run postgraphql/postgraphql --help

To connect to a database and expose the PostGraphQL port try this:

docker run -p 5000:5000 postgraphql/postgraphql --connection postgres://POSTGRES_USER:POSTGRES_PASSWORD@POSTGRES_HOST:POSTGRES_PORT/POSTGRES_DATABASE

Also make sure to check out the forum example and especially step by step tutorial for a demo of a PostGraphQL compliant schema and authentication.

Benefits

PostGraphQL uses the joint benefits of PostgreSQL and GraphQL to provide a number of key benefits.

Automatic Relation Detection

Does your tableā€™s authorId column reference another table? PostGraphQL knows and will give you a field for easily querying that reference.

A schema like:

create table post (
  id serial primary key,
  author_id int non null references user(id),
  headline text,
  body text,
  ...
);

Can query relations like so:

{
  allPosts {
    edges {
      node {
        headline
        body
        author: userByAuthorId {
          name
        }
      }
    }
  }
}

Custom Mutations and Computed Columns

Procedures in PostgreSQL are powerful for writing business logic in your database schema, and PostGraphQL allows you to access those procedures through a GraphQL interface. Create a custom mutation, write an advanced SQL query, or even extend your tables with computed columns! Procedures allow you to write logic for your app in SQL instead of in the client all while being accessible through the GraphQL interface.

So a search query could be written like this:

create function search_posts(search text) returns setof post as $$
  select *
  from post
  where
    headline ilike ('%' || search || '%') or
    body ilike ('%' || search || '%')
$$ language sql stable;

And queried through GraphQL like this:

{
  searchPosts(search: "Hello world", first: 5) {
    pageInfo {
      hasNextPage
    }
    totalCount
    edges {
      cursor
      node {
        headline
        body
      }
    }
  }
}

For more information, check out our procedure documentation and our advanced queries documentation.

Advanced Watch Mode

Running PostGraphQL in watch mode will get you the best experience for iterating on a GraphQL API in the whole GraphQL ecosystem.

postgraphql --watch

PostGraphQL will watch your Postgres database for changes. New tables, updated columns, new procedures, and more! When these changes are detected PostGraphQL will re-create your schema and will automatically update any opened GraphiQL windows with the new schema while preserving your navigation state in the documentation viewer.

Fully Documented APIs

Introspection of a GraphQL schema is powerful for developer tooling and one element of introspection is that every type in GraphQL has an associated description field. As PostgreSQL allows you to document your database objects, naturally PostGraphQL exposes these documentation comments through GraphQL.

Documenting PostgreSQL objects with the COMMENT command like so:

create table user (
  username text non null unique,
  ...
);

comment on table user is 'A human user of the forum.';
comment on column user.username is 'A unique name selected by the user to represent them on our site.';

Will let you reflect on the schema and get the JSON below:

{
  __type(name: "User") { ... }
}
{
  "__type": {
    "name": "User",
    "description": "A human user of the forum.",
    "fields": {
      "username": {
        "name": "username",
        "description": "A unique name selected by the user to represent them on our site."
      }
    }
  }
}

UI For Development Comes Standard

GraphiQL is a great tool by Facebook to let you interactively explore your data. When development mode is enabled in PostGraphQL, the GraphiQL interface will be automatically displayed at your GraphQL endpoint.

Just navigate with your browser to the URL printed to your console after starting PostGraphQL and use GraphiQL with your data! Even if you donā€™t want to use GraphQL in your app, this is a great interface for working with any PostgreSQL database.

Token Based Authorization

PostGraphQL lets you use token based authentication with JSON Web Tokens (JWT) to secure your API. It doesnā€™t make sense to redefine your authentication in the API layer, instead just put your authorization logic in the database schema! With an advanced grants system and row level security, authorization in PostgreSQL is more than enough for your needs.

PostGraphQL follows the PostgreSQL JSON Web Token Serialization Specification for serializing JWTs to the database for your use in authorization. The role claim of your JWT will become your PostgreSQL role and all other claims can be found under the jwt.claims namespace (see retrieving claims in PostgreSQL).

To enable token based authorization use the --secret <string> command line argument with a secure string PostGraphQL will use to sign and verify tokens. And if you donā€™t want authorization, just donā€™t set the --secret argument and PostGraphQL will ignore all authorization information!

Cursor Based Pagination For Free

There are some problems with traditional limit/offset pagination and realtime data. For more information on such problems, read this article.

PostGraphQL not only provides limit/offset pagination, but it also provides cursor based pagination ordering on the column of your choice. Never again skip an item with free cursor based pagination!

Relay Specification Compliant

You donā€™t have to use GraphQL with React and Relay, but if you are, PostGraphQL implements the brilliant Relay specifications for GraphQL. Even if you are not using Relay your project will benefit from having these strong, well thought out specifications implemented by PostGraphQL.

The specific specs PostGraphQL implements are:


Documentation


Contributing

Want to help testing and developing PostGraphQL? Check out the contributing document to get started quickly!

Thanks

Thanks so much to the people working on PostgREST which was definetly a huge inspiration for this project!

The original author of PostGraphQL was @calebmer. The primary maintainer is now @benjie.

Thanks and enjoy šŸ‘