Update docs, getting started guide and mutations

This commit is contained in:
Vikram Rangnekar 2019-10-04 22:20:54 -04:00
parent 50ba6732fe
commit 52ee2cf6a3
5 changed files with 508 additions and 19 deletions

View File

@ -5,10 +5,12 @@
![MIT license](https://img.shields.io/github/license/dosco/super-graph.svg) ![MIT license](https://img.shields.io/github/license/dosco/super-graph.svg)
![Docker build](https://img.shields.io/docker/cloud/build/dosco/super-graph.svg) ![Docker build](https://img.shields.io/docker/cloud/build/dosco/super-graph.svg)
![Cloud native](https://img.shields.io/badge/cloud--native-enabled-blue.svg) ![Cloud native](https://img.shields.io/badge/cloud--native-enabled-blue.svg)
[![Discord Chat](https://img.shields.io/discord/628796009539043348.svg)](https://discord.gg/6pSWCTZ)
Get an instant high performance GraphQL API for Postgres. No code needed. GraphQL is automatically transformed into efficient database queries. Get an instant high performance GraphQL API for Postgres. No code needed. GraphQL is automatically transformed into efficient database queries.
![GraphQL](docs/.vuepress/public/graphql.png?raw=true "") ![GraphQL](docs/.vuepress/public/graphql.png?raw=true "")
![Join Chat](https://discord.gg/NKdXBc "")
## The story of Super Graph? ## The story of Super Graph?
@ -45,7 +47,9 @@ This compiler is what sits at the heart of Super Graph with layers of useful fun
## Contact me ## Contact me
[twitter.com/dosco](https://twitter.com/dosco) [twitter/dosco](https://twitter.com/dosco)
[chat/super-graph](https://discord.gg/6pSWCTZ)
## License ## License

View File

@ -22,7 +22,7 @@ enable_tracing: true
# Watch the config folder and reload Super Graph # Watch the config folder and reload Super Graph
# with the new configs when a change is detected # with the new configs when a change is detected
reload_on_config_change: true reload_on_config_change: false
# File that points to the database seeding script # File that points to the database seeding script
# seed_file: seed.js # seed_file: seed.js

View File

@ -9,6 +9,8 @@ module.exports = {
{ text: 'Deploy', link: '/deploy' }, { text: 'Deploy', link: '/deploy' },
{ text: 'Github', link: 'https://github.com/dosco/super-graph' }, { text: 'Github', link: 'https://github.com/dosco/super-graph' },
{ text: 'Docker', link: 'https://hub.docker.com/r/dosco/super-graph/builds' }, { text: 'Docker', link: 'https://hub.docker.com/r/dosco/super-graph/builds' },
{ text: 'Join Chat', link: 'https://discord.gg/NKdXBc' },
], ],
serviceWorker: { serviceWorker: {
updatePopup: true updatePopup: true

View File

@ -4,30 +4,37 @@ sidebar: auto
# Guide to Super Graph # Guide to Super Graph
Without writing a line of code get an instant high-performance GraphQL API for your Ruby-on-Rails app. Super Graph will automatically understand your apps database and expose a secure, fast and complete GraphQL API for it. Built in support for Rails authentication and JWT tokens. Get an instant high performance GraphQL API for Postgres. No code needed. GraphQL is automatically transformed into efficient database queries. Also Designed to integrate with your Rails apps.
## Features ## Features
- Automatically learns Postgres schemas and relationships
- Supports Belongs-To, One-To-Many and Many-To-Many table relationships
- Works with Rails database schemas - Works with Rails database schemas
- Full text search and aggregations - Automatically learns schemas and relationships
- Belongs-To, One-To-Many and Many-To-Many table relationships
- Full text search and Aggregations
- Rails Auth supported (Redis, Memcache, Cookie) - Rails Auth supported (Redis, Memcache, Cookie)
- JWT tokens supported (Auth0, etc) - JWT tokens supported (Auth0, etc)
- Join database queries with remote data sources (APIs like Stripe, Twitter, etc) - Join with remote REST APIs
- Generates highly optimized and fast Postgres SQL queries - Highly optimized and fast Postgres SQL queries
- Uses prepared statements for very fast Postgres queries - Support GraphQL queries and mutations
- Configure with a simple config file - Configure with a simple config file
- High performance GO codebase - High performance GO codebase
- Tiny docker image and low memory requirements - Tiny docker image and low memory requirements
- Database migrations tool
- Write database seeding scripts in Javascript
## Try it out ## Try the demo app
```bash ```bash
# download super graph source # download the Docker compose config for the demo
git clone https://github.com/dosco/super-graph.git curl -L -o demo.yml https://bit.ly/2mq05lW
# setup the demo rails app & database and run it # setup the demo rails app & database and run it
./demo start docker-compose -f demo.yml run rails_app rake db:create db:migrate db:seed
# run the demo
docker-compose -f demo.yml up
# signin to the demo app (user1@demo.com / 123456) # signin to the demo app (user1@demo.com / 123456)
open http://localhost:3000 open http://localhost:3000
@ -43,7 +50,7 @@ docker website [https://docs.docker.com/docker-for-mac/install/](https://docs.do
#### Trying out GraphQL #### Trying out GraphQL
We currently support the `query` action which is used for fetching data. Support for `mutation` and `subscriptions` is work in progress. For example the below GraphQL query would fetch two products that belong to the current user where the price is greater than 10 We currently fully support queries and mutations. Support for `subscriptions` is work in progress. For example the below GraphQL query would fetch two products that belong to the current user where the price is greater than 10.
#### GQL Query #### GQL Query
@ -65,6 +72,27 @@ query {
} }
``` ```
In another example the below GraphQL mutation would insert a product into the database. The first part of the below example is the variable data and the second half is the GraphQL mutation. For mutations data has to always ben passed as a variable.
```json
{
"data": {
"name": "Art of Computer Programming",
"description": "The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth",
"price": 30.5
}
}
```
```graphql
mutation {
product(insert: $data) {
id
name
}
}
```
The above GraphQL query returns the JSON result below. It handles all The above GraphQL query returns the JSON result below. It handles all
kinds of complexity without you having to writing a line of code. kinds of complexity without you having to writing a line of code.
@ -109,6 +137,325 @@ curl 'http://localhost:8080/api/v1/graphql' \
-H 'content-type: application/json' \ -H 'content-type: application/json' \
-H 'X-User-ID: 5' \ -H 'X-User-ID: 5' \
--data-binary '{"query":"{ products { name price users { email }}}"}' --data-binary '{"query":"{ products { name price users { email }}}"}'
```
## Get Started
Super Graph can generate your initial app for you. The generated app will have config files, database migrations and seed files among other things like docker related files.
You can then add your database schema to the migrations, maybe create some seed data using the seed script and launch Super Graph. You're now good to go and can start working on your UI frontend in React, Vue or whatever.
```bash
# use the below command to download and install Super Graph. You will need Go 1.13 or above
GO111MODULE=on go get -u github.com/dosco/super-graph
# create a new app and change to it's directory
super-graph new blog; cd blog
# setup the app database and seed it with fake data. Docker compose will start a Postgres database for your app
docker-compose run blog_api ./super-graph db:setup
# and finally launch Super Graph configured for your app
docker-compose up
```
Lets take a look at the files generated by Super Graph when you create a new app
```bash
super-graph new blog
> created 'blog'
> created 'blog/Dockerfile'
> created 'blog/docker-compose.yml'
> created 'blog/config'
> created 'blog/config/dev.yml'
> created 'blog/config/prod.yml'
> created 'blog/config/seed.js'
> created 'blog/config/migrations'
> created 'blog/config/migrations/100_init.sql'
> app 'blog' initialized
```
### Docker files
Docker Compose is a great way to run multiple services while developing on your desktop or laptop. In our case we need Postgres and Super Graph to both be running and the `docker-compose.yml` is configured to do just that. The Super Graph service is named after your app postfixed with `_api`. The Dockerfile can be used build a containr of your app for production deployment.
```bash
docker-compose run blog_api ./super-graph help
```
### Config files
All the config files needs to configure Super Graph for your app are contained in this folder for starters you have two `dev.yaml` and `prod.yaml`. When the `GO_ENV` environment variable is set to `development` then `dev.yaml` is used and the prod one when it's set to `production`. Stage and Test are the other two environment options, but you can set the `GO_ENV` to whatever you like (eg. `alpha-test`) and Super Graph will look for a yaml file with that name to load config from.
### Seed.js
Having data flowing through your API makes building your frontend UI so much easier. When creafting say a user profile wouldn't it be nice for the API to return a fake user with name, picture and all. This is why having the ability to seed your database is important. Seeding cn also be used in production to setup some initial users like the admins or to add an initial set of products to a ecommerce store.
Super Graph makes this easy by allowing you to write your seeding script in plan old Javascript. The below file that auto-generated for new apps uses our built-in functions `fake` and `graphql` to generate fake data and use GraphQL mutations to insert it into the database.
```javascript
// Example script to seed database
var users = [];
for (i = 0; i < 10; i++) {
var data = {
full_name: fake.name(),
email: fake.email()
}
var res = graphql(" \
mutation { \
user(insert: $data) { \
id \
} \
}", { data: data })
users.push(res.user)
}
```
You can generate the following fake data for your seeding purposes. Below is the list of fake data functions supported by the built-in fake data library. For example `fake.image_url()` will generate a fake image url or `fake.shuffle_strings(['hello', 'world', 'cool'])` will generate a randomly shuffled version of that array of strings or `fake.rand_string(['hello', 'world', 'cool'])` will return a random string from the array provided.
```
// Person
person
name
name_prefix
name_suffix
first_name
last_name
gender
ssn
contact
email
phone
phone_formatted
username
password
// Address
address
city
country
country_abr
state
state_abr
status_code
street
street_name
street_number
street_prefix
street_suffix
zip
latitude
latitude_in_range
longitude
longitude_in_range
// Beer
beer_alcohol
beer_hop
beer_ibu
beer_blg
beer_malt
beer_name
beer_style
beer_yeast
// Cars
vehicle
vehicle_type
car_maker
car_model
fuel_type
transmission_gear_type
// Text
word
sentence
paragrph
question
quote
// Misc
generate
boolean
uuid
// Colors
color
hex_color
rgb_color
safe_color
// Internet
url
image_url
domain_name
domain_suffix
ipv4_address
ipv6_address
simple_status_code
http_method
user_agent
user_agent_firefox
user_agent_chrome
user_agent_opera
user_agent_safari
// Date / Time
date
date_range
nano_second
second
minute
hour
month
day
weekday
year
timezone
timezone_abv
timezone_full
timezone_offset
// Payment
price
credit_card
credit_card_cvv
credit_card_number
credit_card_number_luhn
credit_card_type
currency
currency_long
currency_short
// Company
bs
buzzword
company
company_suffix
job
job_description
job_level
job_title
// Hacker
hacker_abbreviation
hacker_adjective
hacker_ingverb
hacker_noun
hacker_phrase
hacker_verb
//Hipster
hipster_word
hipster_paragraph
hipster_sentence
// File
extension
mine_type
// Numbers
number
numerify
int8
int16
int32
int64
uint8
uint16
uint32
uint64
float32
float32_range
float64
float64_range
shuffle_ints
mac_address
//String
digit
letter
lexify
rand_string
shuffle_strings
numerify
```
### Migrations
Easy database migrations is the most important thing when building products backend by a relational database. We make it super easy to manage and migrate your database.
```bash
super-graph db:new create_users
> created migration 'config/migrations/101_create_users.sql'
```
Migrations in Super Graph are plain old Postgres SQL. Here's an example for the above migration.
```sql
-- Write your migrate up statements here
CREATE TABLE public.users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name text,
email text UNIQUE NOT NULL CHECK (length(email) < 255),
created_at timestamptz NOT NULL NOT NULL DEFAULT NOW(),
updated_at timestamptz NOT NULL NOT NULL DEFAULT NOW()
);
---- create above / drop below ----
-- Write your down migrate statements here. If this migration is irreversible
-- then delete the separator line above.
DROP TABLE public.users
```
We would encourage you to leverage triggers to maintain consistancy of your data for example here are a couple triggers that you can add to you init migration and across your tables.
```sql
-- This trigger script will set the updated_at column everytime a row is updated
CREATE OR REPLACE FUNCTION trigger_set_updated_at()
RETURNS TRIGGER SET SCHEMA 'public' LANGUAGE 'plpgsql' AS $$
BEGIN
new.updated_at = now();
RETURN new;
END;
$$;
...
-- An exmple of adding this trigger to the users table
CREATE TRIGGER set_updated_at BEFORE UPDATE ON public.users
FOR EACH ROW EXECUTE PROCEDURE trigger_set_updated_at();
```
```sql
-- This trigger script will set the user_id column to the current
-- Super Graph user.id value everytime a row is created or updated
CREATE OR REPLACE FUNCTION trigger_set_user_id()
RETURNS TRIGGER SET SCHEMA 'public' LANGUAGE 'plpgsql' AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
new.user_id = old.user_id;
ELSE
new.user_id = current_setting('user.id')::int;
END IF;
RETURN new;
END;
$$;
...
-- An exmple of adding this trigger to the blog_posts table
CREATE TRIGGER set_user_id BEFORE INSERT OR UPDATE ON public.blog_posts
FOR EACH ROW EXECUTE PROCEDURE trigger_set_user_id();
``` ```
@ -150,7 +497,7 @@ query {
} }
``` ```
### Complex queries (Where) ### Advanced queries
Super Graph support complex queries where you can add filters, ordering,offsets and limits on the query. Super Graph support complex queries where you can add filters, ordering,offsets and limits on the query.
@ -187,7 +534,7 @@ contains | column: { contains: [1, 2, 4] } | Is this array/json column a subset
contained_in | column: { contains: "{'a':1, 'b':2}" } | Is this array/json column a subset of these value contained_in | column: { contains: "{'a':1, 'b':2}" } | Is this array/json column a subset of these value
is_null | column: { is_null: true } | Is column value null or not is_null | column: { is_null: true } | Is column value null or not
### Aggregation (Max, Count, etc) ### Aggregations
You will often find the need to fetch aggregated values from the database such as `count`, `max`, `min`, etc. This is simple to do with GraphQL, just prefix the aggregation name to the field name that you want to aggregrate like `count_id`. The below query will group products by name and find the minimum price for each group. Notice the `min_price` field we're adding `min_` to price. You will often find the need to fetch aggregated values from the database such as `count`, `max`, `min`, etc. This is simple to do with GraphQL, just prefix the aggregation name to the field name that you want to aggregrate like `count_id`. The below query will group products by name and find the minimum price for each group. Notice the `min_price` field we're adding `min_` to price.
@ -239,6 +586,141 @@ query {
} }
``` ```
## Mutations
In GraphQL mutations is the operation type for when you need to modify data. Super Graph supports the `insert`, `update` and `delete` database operations. Here are some examples.
When using mutations the data must be passed as variables since Super Graphs compiles the query into an prepared statement in the database for maximum speed. Prepared statements are are functions in your code when called they accept arguments and your variables are passed in as those arguments.
### Insert
```json
{
"data": {
"name": "Art of Computer Programming",
"description": "The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth",
"price": 30.5
}
}
```
```graphql
mutation {
product(insert: $data) {
id
name
}
}
```
### Bulk insert
```json
{
"data": [{
"name": "Art of Computer Programming",
"description": "The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth",
"price": 30.5
},
{
"name": "Compilers: Principles, Techniques, and Tools",
"description": "Known to professors, students, and developers worldwide as the 'Dragon Book' is available in a new edition",
"price": 93.74
}]
}
```
```graphql
mutation {
product(insert: $data) {
id
name
}
}
```
### Update
```json
{
"data": {
"price": 200.0
},
"product_id": 5
}
```
```graphql
mutation {
product(update: $data, id: $product_id) {
id
name
}
}
```
### Bulk update
```json
{
"data": {
"price": 500.0
},
"gt_product_id": 450.0,
"lt_product_id:": 550.0
}
```
```graphql
mutation {
product(update: $data, where: {
price: { gt: $gt_product_id, lt: lt_product_id }
}) {
id
name
}
}
```
### Delete
```json
{
"data": {
"price": 500.0
},
"product_id": 5
}
```
```graphql
mutation {
product(delete: true, id: $product_id) {
id
name
}
}
```
### Bulk delete
```json
{
"data": {
"price": 500.0
}
}
```
```graphql
mutation {
product(delete: true, where: { price: { eq: { 500.0 } } }) {
id
name
}
}
```
### Using variables ### Using variables
Variables (`$product_id`) and their values (`"product_id": 5`) can be passed along side the GraphQL query. Using variables makes for better client side code as well as improved server side SQL query caching. The build-in web-ui also supports setting variables. Not having to manipulate your GraphQL query string to insert values into it makes for cleaner Variables (`$product_id`) and their values (`"product_id": 5`) can be passed along side the GraphQL query. Using variables makes for better client side code as well as improved server side SQL query caching. The build-in web-ui also supports setting variables. Not having to manipulate your GraphQL query string to insert values into it makes for cleaner

View File

@ -10,7 +10,8 @@ CREATE TABLE public.users (
---- create above / drop below ---- ---- create above / drop below ----
-- Write your migrate down statements here. If this migration is irreversible -- Write your down migrate statements here. If this migration is irreversible
-- Then delete the separator line above. -- then delete the separator line above.
DROP TABLE public.users DROP TABLE public.users