Coder Social home page Coder Social logo

graphile / crystal Goto Github PK

View Code? Open in Web Editor NEW
12.4K 125.0 557.0 56.22 MB

๐Ÿ”ฎ Graphile's Crystal Monorepo; home to Grafast, PostGraphile, pg-introspection, pg-sql2 and much more!

Home Page: https://graphile.org/

License: Other

JavaScript 2.11% Shell 0.34% TypeScript 92.88% CSS 0.04% PLpgSQL 4.63%
graphql postgres typescript postgraphql schema graphql-api automatic-api graphile graphql-js pg

crystal's Introduction

๐Ÿ”ฎ Graphile's Crystal Monorepo

GitHub Sponsors Patreon sponsor button Discord chat room Follow

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.
  • 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
  • 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/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.

And please give some love to our featured sponsors ๐Ÿคฉ:

The Guild
The Guild
*
Dovetail
Dovetail
*
Netflix
Netflix
*
Stellate
Stellate
*
Steelhead
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.

crystal's People

Contributors

ab-pm avatar angelosarto avatar benjie avatar bradleyayers avatar calebmer avatar csnweb avatar dargmuesli avatar dependabot[bot] avatar dodobibi avatar enisdenjo avatar ferdinandsalis avatar greenkeeperio-bot avatar hansololai avatar innermatrix avatar jamesallain avatar jcgsville avatar jemgillam avatar jvandermey avatar langpavel avatar mathroc avatar mattbretl avatar michaelbeaumont avatar petetnt avatar purge avatar singingwolfboy avatar snyk-bot avatar speller avatar tim-field avatar timostolz avatar xanderg2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

crystal's Issues

Error pg-connection-string testing

Hi Calebmer
after following the instructions in https://github.com/calebmer/postgraphql/tree/master/examples/forum

postgraphql postgres://localhost:5432 --schema forum_example --development
doesn't work with or without user:password
Error is:

module.js:327
throw err;
^

Error: Cannot find module 'pg-connection-string'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object. (/usr/local/lib/node_modules/postgraphql/dist/main.js:18:27)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:134:18)
at node.js:962:3

Regards
rbonazzo

Views (and every other table) requiring a primary key

It seems it is designed this way, but maybe for anyone Googling the error, it'd be good to get it in writing:

Error: PostgreSQL schema 'memberships' contains table 'product_stock' which does not have any primary key. To generate a GraphQL schema all tables must have a primary key.

Or is there a way around it? You seem to generate your own ID's anyway, so maybe it could be done for the items where there's no primary key set?

How to force valid JWT tokens

I love this project, it is so concise and to the point, especially the scope of what it is trying to achieve!

So I was able to generate a token and have posgraphql evaluate the claim:

curl -XPOST -H "Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJwb3N0Z3JhcGhxbCIsInJvbGUiOiJncmFwaHFsIiwidXNlcl9pZCI6Mn0.oQVZfTK-LdC1btVvR8OrzRAhSPEKsFJHeqxhF9xk8rc" -H 'Content-Type:application/graphql' -d '{ searchPosts(search:"s",first:2){nodes{rowId}}}' 127.0.0.1:3000

So I was able to get it to return valid date for a valid token containing a valid role.

However, I also able to get the same data with an empty token:

curl -XPOST -H "Authorization:Bearer " -H 'Content-Type:application/graphql' -d '{ searchPosts(search:"s",first:2){nodes{rowId}}}' 127.0.0.1:3000

Is there a way to mandate a non-empty token if the secret flag has been set (other than say enforcing this with an upstream nginx proxy)?

Any other non-empty token string appears to evaluate correctly (it would be nice to get a 403 instead of a 500, but that's a separate issue).

My vision for the future of PostGraphQL

Hi, Iโ€™m @calebmer, author of PostGraphQL a framework which turns your PostgreSQL database into a GraphQL server with minimal configuration. In this issue, I want to share my vision for the future PostGraphQL.

As you may know, PostGraphQL currently does one thing fairly well: turns a PostgreSQL database into a GraphQL API. You also may have heard of PostgREST which I contributed to in the past, itโ€™s written in Haskell you should check it out. Similarly PostgREST also does one thing fairly well: turns a PostgreSQL database into a REST API.

Tools like these have a very high utility for certain use cases, but at the same time they are inflexible. What if I wanted a GraphQL API for my MySQL database using PostGraphQL? Well that wouldnโ€™t be too easy. Every time we create another one of these tools we are repeating a lot of logic, because every API is generally just doing the same four things: creates, reads, updates, and deletes. CRUD.

Itโ€™s weird that we standardize on front-end frameworks like React or Angular, but our backends which are often just glorified CRUD interfaces get written from scratch.

I want PostGraphQL to be an opinionated tool thatโ€™s part of a more powerful ecosystem. An ecosystem that is focused on abstracting the data layer from the data interface. So instead of having one tightly coupled tool that look like:

PostgreSQL โ†’ GraphQL

We could have two loosely coupled tools that look like:

PostgreSQL โ†’ Interface โ†’ GraphQL

One tool that turns our PostgreSQL database into an abstract interface, and one that turns our abstract interface into a GraphQL API.

When we add that extra layer, we can start interchanging parts. Instead of PostgreSQL โ†’ Interface โ†’ GraphQL, we could have MySQL โ†’ Interface โ†’ GraphQL for half the effort. We also get the advantage of when our Interface โ†’ GraphQL tool improves, both toolchains benefit.

This is an ambitious goal, but it wouldnโ€™t be the first time I have tried it. Iโ€™ve had this vision for a long time. Itโ€™s been about two years in the making. It started when I was contributing to PostgREST and contributors were talking about adding GraphQL support (at the time I was opposed, isnโ€™t that ironic ๐Ÿ˜Š). After I stopped contributing to PostgREST I tried building this very idea, you can see my efforts in the Ardite organization. This approach failed for a couple of reasons which I wonโ€™t go into, but when it failed I decided to narrow my scope and just focus on PostgreSQL and GraphQL. Thatโ€™s where PostGraphQL was born. Iโ€™m returning to this idea now because we just finished talking to a client who would have benefitted greatly if this technology existed.

Now that youโ€™ve hezard the vision, letโ€™s talk implementation.

Timeline

Getting to the point where we have MySQL to GraphQL tooling is going to take a lot of effort, so weโ€™re going to focus on making PostGraphQL the best possible product it can be for now. Hereโ€™s my timeline to get that done:

  1. Implement authentication. In order to do this in the best way possible we will need the PostgreSQL to GraphQL interface built, this might take a bit. I have the core code already written but it will take a while to reach feature parity with PostGraphQL. Once the interface is built, layering authentication on top will be much easier than it is today.
  2. Documentation binge. We need a website for PostGraphQL with some really good documentation. In this website Iโ€™d also like to write a tutorial for how to design a good PostgreSQL database schema.
  3. Create a CMS on top of the abstract interface weโ€™ve built. At this point weโ€™ll start to break up all the pieces that compose PostGraphQL and allow them to be iterated on separately. Iโ€™ve thought about building a CMS on top of GraphQL, but it turns out GraphQL has too few opinions to make that tech really work.

When we are done, I believe we will have created software that will make the lives of many engineers much easier. Developers will be able to iterate faster and build apps quicker. Development shops will be able to take on more clients for lower prices which means more businesses can be created with a strong software core. But itโ€™s a lot of work, and Iโ€™m going to need help.

Iโ€™ve posted the interface I have so far in this Gist if you want to start taking a look. I donโ€™t know when I will be comfortable sharing the entire new PostGraphQL codebase, but once Iโ€™m done with that, Iโ€™ll need a lot of help with steps 2 and 3.

If anyone is willing to start designing and building a website, I would be greatly appreciative. If anyone wants to help write examples like the Relay example @ferdinandsalis has been working on in #66, that would also be awesome.

If anyone wants to reach out to me personally, my email is [email protected]

forum example: search by rowId not working

personNodes by id (base64 table+id) works

This works:

{
  personNodes(id: "cGVyc29uOjI=") {
    nodes {
      id
      familyName
    }
  }
}

this does not:

{
  personNodes(rowId: 1) {
    nodes {
      id
      familyName
    }
  }
}

I've been checking the code and it looks it is trying to find a column name "rowId" which doesn't exist

Pure GraphQL-compliant version

Have you thought about just making a pure GraphQL version, sans-Relay?

Maybe making Relay-compliancy an option or add-on?

Clean reflection of many-to-many relations.

I'm having trouble modelling many-to-many relations which reflect a straightforward GraphQL interface.

In the documentation, 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:

{
  postNodes {
    nodes {
      headline
      body
      author: userByAuthorId {
        name
      }
    }
  }
}

Which works fine for one-to-many relations. However, I'm trying to write a schema which would, for example, allow a post to have many authors and still allow the same kind of straightforward queries:

{
  postNodes {
    nodes {
      headline
      body
      authors: someQueryName {
        name
      }
    }
  }
}

Using a relation table provides a postAuthorsByPersonIdAndPostId which seems tricky to use properly, and though I think I could write a query function providing computed columns, I'm not entirely sure that's the right way to proceed.

Then again, I'm basing my hacks on code from the kitchen sink example and integration code. I haven't found much mention of many-to-many relations here yet. ๐Ÿ˜ข

computed column yields `error: malformed array literal โ€ฆ`

I am trying to add a computed column (see below). I have tested the procedure and it returns exactly the row I ask for. However when execute it in a graphql query I get the following error error: malformed array literal: "[34,24,null]".

-- Computed Columns

create function artwork_cover_url(artwork artwork) returns varchar as $$
  select i.uri as cover_url
    from artwork_image as ai
    join image as i
      on ai.image_id = i.id
    where ai.artwork_id = artwork.id
    order by ai.priority desc limit 1
$$ language sql stable
set search_path from current;

psql test output โ€”

artwork_cover_url
2e705a23116e9512b2dcbd1768bde1893e648fde.jpg
(1 row)

Natural vs opaque surrogate keys for defining associations

For some applications have separate ID and rowId fields increase complexity a lot(I am porting ng-admin to use postgraphql generated endpoint).

As I understand - main reason for using special ID type is to provide global unique object identifier across all entities/tables. This requirement also can be solved by usage of UUID as primary key for tables.

That's why I would like to see parameter(for example : --uuid-based-schema) that will remove rowId and will use ordinary id as key for graphql queries.

I can work on this feature and would like to hear any thoughts/concerns before designing it.

Argument "id" has invalid value 1. Expected type "ID", found 1.

Maybe I'm doing something wrong, I don't know GraphQL yet, but this is a simple way to reproduce what I'm seeing. I can't query a table by id.

createdb postgraphql
psql postgraphql -c "create table foo(id integer primary key, name text);"
psql postgraphql -c "insert into foo (id, name) values (1, 'first foo');"
psql postgraphql -c "insert into foo (id, name) values (2, 'second foo');"

postgraphql postgres://localhost:5432/postgraphql

curl -XPOST -H "Content-Type:application/graphql" -d 'query { foo(id: 1) { id, name } }' http://localhost:3000/
{"errors":[{"message":"Argument \"id\" has invalid value 1.\nExpected type \"ID\", found 1.","locations":[{"line":1,"column":17}]}]}

Authentication endpoint to generate JWT tokens

Great project!

I am having trouble working out where I generate the JWT token. Your docs provide a really good description of how you can see the details of a passed in token, so I assume that you are meant to create a JWT token in another service and just have the same secret as you have in postgraphql. Is this correct?

If so, is it possible to add an endpoint to postgraphql to allow users to authenticate with a postgresql login role and password and have postgraphql generate and return a JWT token for use with graphql queries?

Thanks.

Cannot find module './catalog.js'

I'm getting the following error with all commands,

node v5.11.0
npm 3.8.0
[email protected]

Maybe related to this commit 4bdc2b1 ?

postgraphql --help
module.js:341
    throw err;
    ^

Error: Cannot find module './catalog.js'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/tim/npm/lib/node_modules/postgraphql/dist/postgres/getCatalog.js:19:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/tim/npm/lib/node_modules/postgraphql/dist/createGraphqlSchema.js:7:19)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)

Where JWT token is read from and how to use it with GraphiQL?

In the documentation, it says:

After a JSON Web Token has been verified and decoded, the resulting claims will be serialized to the PostgreSQL database in two ways:

However, it is not clear where the JWT token is read from?

Also, since I'm using database roles to limit access to the database objects, it would also be very useful to use JWT with GraphiQL - this would allow me to easily test whether all permissions are set correctly for my queries for various roles. Any idea how to do it?

Doesn't work with `interval` field

One of my databases has a table that contains an interval field and postgraphql doesn't work with the DB. Any request to any table returns the following error (assuming the table myTable has an interval field called duration):

{
  "errors": [
    {
      "message": "Query.myTableNodes(duration:) argument type must be Input Type but got: Interval."
    }
  ]
}

no such file or directory, stat '/usr/local/lib/node_modules/postgraphql/assets/favicon.ico'

I installed with "npm install -g postgraphql" then tried to run it against a local database. It outputs the following error and exits.

postgraphql postgres://localhost:5432/foo
Error: ENOENT: no such file or directory, stat '/usr/local/lib/node_modules/postgraphql/assets/favicon.ico'
    at Error (native)
    at Object.fs.statSync (fs.js:892:18)
    at favicon (/usr/local/lib/node_modules/postgraphql/node_modules/serve-favicon/index.js:64:15)
    at /usr/local/lib/node_modules/postgraphql/dist/createServer.js:65:46
    at next (native)
    at step (/usr/local/lib/node_modules/postgraphql/dist/createServer.js:43:191)
    at /usr/local/lib/node_modules/postgraphql/dist/createServer.js:43:451
    at /usr/local/lib/node_modules/postgraphql/dist/createServer.js:43:99
    at createServer (/usr/local/lib/node_modules/postgraphql/dist/createServer.js:94:16)
    at /usr/local/lib/node_modules/postgraphql/dist/main.js:73:56
    at next (native)
    at step (/usr/local/lib/node_modules/postgraphql/dist/main.js:30:191)
    at /usr/local/lib/node_modules/postgraphql/dist/main.js:30:368

Disable auto updatable views

Hey there,

I am playing with postgraphql with one of our current schemas and noticed that if i create a view to a table in another schema it also generates the mutations for that view.

I would prefer it not to show those mutations, and have tried creating rules set to DO NOTHING for the view, but the graphql introspection is still showing the mutations.

Is there a way to tell postgraphql to not generate mutations for particular views?

Relay mutation types support

Hi, I'm trying to write Relay client backed by postgrqphql, but I'm having trouble with RANGE_ADD mutation type, which I want to use for adding a new person to the list of persons.

InsertPersonPayload type only contains person: Person and clientMutationId: String fields, but according to relay documentation this mutation type requires a parent, a connection, and the name of the newly created edge from the payload to be specified.

I'm new to GraphQL and Relay and maybe I'm missing something here, but it seems to me that with current mutation payloads it is not possible to define all Relay mutation types. I checked how Reindex solves this and I think we need to add a field containing newly inserted edge (personEdge) and a viewer field that will act as a single entry node allowing us to access connections (like personNodes) that are currently available only in Query type. The single entry node field was already mentioned in #38 but in the context of queries.

For production, do I need PM2 or what?

Hi. To make the server run in background and restart on failure and start automatically on server reboot, what would be the solution?

I read about PM2 - is it suitable, or is there an easier way?

Some example curl commands would be helpful

It would be nice if the README or forum example had some sample curl/wget commands to help one get started. As someone who is just experimenting with postgraphql and GraphQL in general, I would really appreciate it!

For instance, I am querying:

{post {id}}

The error message Field "post" argument "id" of type "ID!" is required but not provided. is not so helpful!

List query filter improvements

Deprecation of existing list

Some of my applications rely heavily on current implementation. I think removal should be done only after similar mechanism will be developed. Creating procedures for each entity is rather time consuming.

New filter syntax suggestion:

One of the possible solutions is to use Mongo like syntax http://rest-layer.io/#filtering

userNodes(filters:UserFilters,order:UserOrdering,pagination:Pagination)

UserFilters
{
  login: StringFilters
  email: StringFilters
  birthdate: DateFilters
}

StringFilters
{
 eq: String
 like: String
 regex: String
}

DateFilters
{
 gt: Date
 ge: Date
 between: [Date,Date]
}

Each Filter can also be a union type:

StringFilters = String | StringFiltersExtended

StringFiltersExtended
{
 eq: String
 like: String
 regex: String
}

By default equality filters is performed. That allow keep compatibility with previous syntax(in case if all fields will be listed in query itself)

In this way we will be able to support specific operators for different types. Otherwise this can be parametrized type with (eq,gt,ge,le,etc..) operators

Multiple databases support

Is there anyway to support multiple databases? Because of customer security concerns, we have one database per customer with each database having the same schema as the others. When a customer logins in, they enter three pieces of information: database name, username, and password. After they login, they are automatically linked to the database they specified (user authentication information is stored inside the database they specified). For enterprise customers, this is very important. Also it helps us scale the database for larger customers and if one database goes down, the others are not affected.

How would I query with UUID id types?

I have an existing schema that uses UUIDs for table IDs. I'm finding I get an error when trying to query a field.

{
  authorizations(id: "40fbe19f-1500-4ff7-a2b1-f5d2108a30d1") {
    algorithm
    expiresAt
    issuedAt
    issuerId
    realm
  }
}
{
  "data": {
    "authorizations": null
  },
  "errors": [
    {
      "message": "Invalid ID '40fbe19f-1500-4ff7-a2b1-f5d2108a30d1'.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "stack": "Error: Invalid ID '40fbe19f-1500-4ff7-a2b1-f5d2108a30d1'.\n    at exports.fromID.encodedString (/usr/local/lib/node_modules/postgraphql/dist/graphql/types.js:48:27)\n    at /usr/local/lib/node_modules/postgraphql/dist/graphql/query/createSingleQueryField.js:47:39\n    at /usr/local/lib/node_modules/postgraphql/dist/graphql/resolveTableSingle.js:107:22\n    at next (native)\n    at step (/usr/local/lib/node_modules/postgraphql/dist/graphql/resolveTableSingle.js:17:191)\n    at /usr/local/lib/node_modules/postgraphql/dist/graphql/resolveTableSingle.js:17:451\n    at /usr/local/lib/node_modules/postgraphql/dist/graphql/resolveTableSingle.js:17:99\n    at /usr/local/lib/node_modules/postgraphql/dist/graphql/resolveTableSingle.js:116:18\n    at resolveOrError (/usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:457:12)\n    at resolveField (/usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:448:16)\n    at /usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:256:18\n    at Array.reduce (native)\n    at executeFields (/usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:254:50)\n    at executeOperation (/usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:196:10)\n    at /usr/local/lib/node_modules/postgraphql/node_modules/graphql/execution/execute.js:114:13\n    at new Promise (/usr/local/lib/node_modules/postgraphql/node_modules/core-js/library/modules/es6.promise.js:193:7)"
    }
  ]
}

GraphiQL has no problem generating the Queries and Mutations.

Awesome project btw.

Question: Input validation

I've been playing around a bit with Postgraphql (together with Vue.js) and I'm impressed.

What is a good way to handle input validation. As I understand it, I can with the express middle-ware use Postgraphql as a start-backend for a frontend project.

But how do I make sure some input doesn't compromise the site? Such as XSS or SQL injections. It's very tempting to just let the frontend mutate (pending auth) through GraphQL, but is it safe?

Error: Schema must contain unique named types but contains multiple types named "ID".

Tried to extend generated schema, got error from header.

Code to reproduce(working in modified main.js from this project):
import {parse, extendSchema} from 'graphql';
...
Before running server: const extendedSchema = extendSchema( graphqlSchema,parse('extend type RootQuery{ id1: String}'));

During debugging found that IDType from 'types.js' clashes with default 'ID' defined internally. For some reason this validation only failing when I am extending created schema.

Following debug output is from https://github.com/graphql/graphql-js/blob/master/src/type/schema.js#L222 after calling extendSchema function :

map[type.name] = GraphQLScalarType { name: 'ID', description: 'A globally unique identifier used to refetch an object or as a key for a cache. It is not intended to be human readable.', _scalarConfig: { name: 'ID', description: 'A globally unique identifier used to refetch an object or as a key for a cache. It is not intended to be human readable.', serialize: [Function], parseValue: [Function], parseLiteral: [Function] } }

type = GraphQLScalarType { name: 'ID', description: 'The IDscalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as"4") or integer (such as 4) input value will be accepted as an ID.', _scalarConfig: { name: 'ID', description: 'The IDscalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as"4") or integer (such as 4) input value will be accepted as an ID.', serialize: [Function: String], parseValue: [Function: String], parseLiteral: [Function: parseLiteral] } }

This can be easily solved by renaming ID type to EntityID

Multiple JWT secrets to support rolling change

Hi there,

I really like your PG JWT spec and think its a good idea to standardise so that people can use both postgrest and/or postgraphql.

Just wondering what your thoughts are around allowing people to put two secrets eg a comma separated list for the --secret parameter when starting postgraphql. Both of these would be valid and perhaps it would try the first one and fallback to the second one.

The reason for this is to support the ability to do a rolling change of your JWT secret across your services without having to deploy them at EXACTLY the same time.

For example if you have a user service separate from Postgraphql that generates the tokens, and you want to use them with postgraphql, both services need to have the same secret. When you need to change the secret because of a compromise or general security policy to rotate secrets it would be heaps easier to allow postgraphql to accept the old one AND the new one for a while until all services have been swapped to the new secret and the old JWTs have expired. Then you can remove the old secret from all services and only have the new one.

Does that sound like a reasonable request, or is there another way to handle a JWT secret change? Or perhaps I am totally misunderstanding how the secret works... ๐Ÿ˜•

Single entry node

Relay (currently) doesn't support connections / array nodes without arguments as entry nodes (see facebook/relay#112 for the rationale).

In terms of the classic use case for relay, where it gets used to resolve the data structure for a given page, that kind of structure (viewer) actually makes sense, as the viewer would be representative of the page you're currently on and would then resolve data starting from that node.

So the current approach for most relay-compatible GraphQL endpoints is to implement a single(ton) viewer node (which sits alongside the node node as the only entry nodes), onto which all other nodes get joined.

"schema 'public' contains table 'geography_columns'"

I think there is an issue with PostGIS which I can't see in the public schema from PyCharm but postgraphql apparently can and throws an error on.

Error: PostgreSQL schema 'public' contains table 'geography_columns' which does not have any primary key. To generate a GraphQL schema all tables must have a primary key.

Timestamps seem not to work

Hi,
I played around with the forum example and added some timestamps. It seems like the postgraphql server is not able to read them. The query throws the following error:

//query
{
  post(id: "cG9zdDox") {
    id
    createdAt
  }
}

//result
{
  "data": {
    "post": {
      "id": "cG9zdDox",
      "createdAt": null
    }
  },
  "errors": [
    {
      "message": "Cannot read property '_scalarConfig' of undefined",
      "stack": "TypeError: Cannot read property '_scalarConfig' of undefined\n    at serialize (/workspace/postgraphql/examples/forum/node_modules/graphql/type/definition.js:170:28)\n    at GraphQLScalarType.serialize (/workspace/postgraphql/examples/forum/node_modules/graphql/type/definition.js:171:14)\n    at completeLeafValue (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:606:37)\n    at completeValue (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:560:12)\n    at completeValueCatchingError (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:477:21)\n    at resolveField (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:450:10)\n    at /workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:256:18\n    at Array.reduce (native)\n    at executeFields (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:254:50)\n    at completeObjectValue (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:648:10)\n    at completeValue (/workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:571:12)\n    at /workspace/postgraphql/examples/forum/node_modules/graphql/execution/execute.js:524:14\n    at process._tickCallback (node.js:382:9)"
    }
  ]
}

//post table
create table post (
  id               serial not null primary key,
  author_id        int not null references person(id),
  headline         text not null,
  topic            post_topic,
  body             text,
  created_at       timestamp with time zone
);

Is this a know issue?

Embedded / Library Usage

Stemming from a gitter discussion.

I'm wondering what @calebmer and others thoughts are surrounding using postgraphql in an embedded or library fashion. I'm working on an express app right now that will be querying an external graphql server for its user-facing functionality. Internally, the app has a very simple postgres DB for storing users, and I'd like to expose a graphql interface to it for building an admin dashboard. I've been able to make it work by basically copying the logic from createServer and implementing it in an Express route.

One potential thing I could see being useful it the ability to specify the client. I'm using knex everywhere else in the app, but for this portion I need to manually import pg and specify the client.

Authorization and Authentication

Hello, I want to begin with saying this project looks promising!

I tried looking through the documentation and the example schema, but I still can't find anything of how you would go about handling authenticating a client using postgraphql. Is there any examples or documentation of this? I haven't read through the source code yet, but I guess this should be documented, authorization can of course be handled by postgres itself, but authentication is another beast.

Thank you!

Cross Origin Requests

Thank you for writing this.

I'm wondering if postgraphql could enable cross origin requests by default. As it's not currently possible to talk to it from a Relay application without setting up a proxy or the like.

I see this ( accidental ) pull request. 4211c77

Wondering if this would be a good approach to take

forum example: how to use search operators

thanks for the kool project! looks primising.

I was wondering how to use the search operators (e.g. like givenName: '%partOfName%')

Do we have to extend the exposed methods? is that even possible?

thanks!

Schema validation error when using enum in two tables

I have following schema:

create type user_opinion as enum ('pro','cons');
create table user_view(id serial primary key,view user_opinion);
create table argument(id serial primary key,side user_opinion);

When I am trying to start postgraphql it gives me error:

Error: Schema must contain unique named types but contains multiple types named "UserOpinion".
    at invariant (/usr/lib/node_modules/postgraphql/node_modules/graphql/jsutils/invariant.js:19:11)
    at typeMapReducer (/usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:207:29)
    at /usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:234:22
    at Array.forEach (native)
    at /usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:225:37
    at typeMapReducer (/usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:236:7)
    at /usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:234:22
    at Array.forEach (native)
    at /usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:225:37
    at typeMapReducer (/usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:236:7)
    at Array.reduce (native)
    at new GraphQLSchema (/usr/lib/node_modules/postgraphql/node_modules/graphql/type/schema.js:104:34)
    at schema (/usr/lib/node_modules/postgraphql/dist/graphql/createSchema.js:25:39)
    at /usr/lib/node_modules/postgraphql/dist/createGraphqlSchema.js:32:57
    at next (native)
    at step (/usr/lib/node_modules/postgraphql/dist/createGraphqlSchema.js:17:191)

Schema validator works using reference comparison(===), so that can be fixed by using cache by name for enum types in https://github.com/calebmer/postgraphql/blob/master/src/graphql/getColumnType.js#L113.

Schema changes

Hi,
currently it seems that I have to restart the postgraphql server when the schema changes.
This will be often the case in my current project. Is there any way to tell the postgraphql process to rescan the schema without restarting it? This would be absolutely awesome.
Thanks for any tips and this awesome project!
Daniel

password authentication failed for user

I expect that this is user error, I'm new to PostGress, so apologies in advance.

tim~> psql books
psql (9.5.3)
Type "help" for help.

books=# select * from author;
 id | first_name | last_name 
----+------------+-----------
  1 | Tom        | McCarthy
(1 row)

books=# \q
tim~>postgraphql postgres://localhost:5432/books --development
GraphQL server listening at http://localhost:3000/ ๐Ÿš€

So far so good, postgess is running on port 5432. I can also connect fine with pgAdmin
But any attempts to use the service result in

{
  "errors": [
    {
      "message": "password authentication failed for user \"tim\""
    }
  ]
}

Any clues would be appreciated

Approaches to JSON

So I am new to GraphQL and not a DBA (though I did sleep at a Holiday inn Express)....

I am curious if postgraphql can deal with me putting JSON into Postgres. I found this reference: https://www.compose.io/articles/is-postgresql-your-next-json-database/

Is this something that can be approached by postgraphql in some way? Or do I need to map my JSON (really JSON-LD using the schema.org vocabulary) into a native shema? So for example the JSON-LD found at the the page http://schema.org/Person Could it be mapped into a schema and served?

Querying null or not null values

Hi,
we are evaluating this awesome piece of software ! And it looks really amazing, thank you very much!

I'd like to know if there is a way to query null or not null values.

Something like:


{
    myTestQuery(paramOne: "paramOneValue") {
        totalCount
        nodes {
            consumerCategories(orderBy: position, deletedAt: !null) {
                nodes: {
                    rowId
                    name
                }
            }
        }
    }
}

Thanks

Xavier

Aliasing undesirable field names

It seems like what a lot of people find undesirable about PostGraphQL is how fields are named. How can we build a system (whether it be a JSON map or otherwise) which allows people to rename automatically named fields?

Any ideas are welcome, I'm have no ideas at the moment.

Version check returning undefined

image

Could this be due to
line 14 in main.js const manifest = readFileSync(path.resolve(__dirname, '../package.json'))
causing .version(manifest.version) to fail?

SyntaxError: Use of const in strict mode.

I'm on Ubuntu 14.04.3 LTS using nodejs v0.10.25. Installed with sudo npm install -g postgraphql. Tried to start the forum example and got the SyntaxError: Use of const in strict mode. error.

morabaraba@morabaraba-VirtualBox:~$ postgraphql postgres://localhost:5432/mydb --schema forum_example --development

/usr/local/lib/node_modules/postgraphql/dist/main.js:34
const manifest = JSON.parse((0, _fs.readFileSync)(_path2['default'].resolve(__
^^^^^
SyntaxError: Use of const in strict mode.
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
morabaraba@morabaraba-VirtualBox:~$ ^C
morabaraba@morabaraba-VirtualBox:~$ postgraphql --help

/usr/local/lib/node_modules/postgraphql/dist/main.js:34
const manifest = JSON.parse((0, _fs.readFileSync)(_path2['default'].resolve(__
^^^^^
SyntaxError: Use of const in strict mode.
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
morabaraba@morabaraba-VirtualBox:~$ nodejs -v
v0.10.25

Any suggestion or log files I can go scratch in?

Subscriptions example

Where can I find a sample implementation of subscriptions?
In the GraphQL blog it is too much theoretical... at least for my preparation.

Cheers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.