EzDev.org

postgraphql

postgraphql - A GraphQL API created by reflection over a PostgreSQL schema.


Go-Swagger and null boolean values

Swagger 3.0 supports multiple types and I can have bool or null. But go-swagger supports swagger 2.0.

Is there way to accept arbitrary type in go-swagger or accept true,false,null on some property?


Source: (StackOverflow)

Using an Array in author_id int references user(id)

On https://github.com/calebmer/postgraphql the author shows a schema:

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

How would I have to rewrite the schema if I would like to cite multiple authors and reference them using an array? Would it be: author_id int[] non null references user(id)?


Source: (StackOverflow)

Trouble using Ember graphql-adapter and postgraphql

Ember and Graphql are both new to me and i'm trying to get my application working with Postgraphql without success

I use Ember and https://github.com/alphasights/ember-graphql-adapter but the query made by ember-graphql-adapter doesn't match the query needed by Postgraphql

I want to get a company in my DB, the query working with Postgraphql is:

query {
  companiesNodes(rowId: 1) {
    nodes {
        id
        rowId
        name
    }
  }   
}

But my app is sending this payload:

query {
  companies(id: 1) {
      id
      rowId
      name
  }
}

How can i modify the second query sent by Ember-graphql-adapter to be wrapped like the first one ?


Source: (StackOverflow)

How can I use postgraphQL in conjunction with ReactQL

I'd like to use the postgraphQL library to auto-generate my graphql schema from a postgres database. I've used this in express apps previously, but I'm trying to make it work with the ReactQL starter kit.

In an express app server file, I've imported postgraphql and then used something like:

app.use(postgraphql(endpoint, schema, {options}));

Seems like the syntax is probably similar with the Koa server in ReactQL, but I'm not quite sure where to put it.

Update: I got it working by adding the code above into the /kit/entry/server.js file in ReactQL. Maybe someone can point out whether or not that's a good practice if it's supposed to occur somewhere else, like in app.js.

Update 2: While the above seems to work (I can hit graphiql and see my schema), I'm getting this message in the terminal:

Error:  Can't set headers after they are sent.

and this in the browser console:

PostGraphQL: Listening for server sent events
PostGraphQL: Failed to connect to server

Source: (StackOverflow)

Graphql date field type must be Output Type but got: undefined

I have a graphql server running with node/expres and ES6, I am trying to migrate to typescript, when I want to do graphql schema I have experiencing some problems with date types. I know that graphql does not contain a native date type, but in my ES6 implementation, I have used graphql-date to suply this limitation.

import {
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLID,
} from 'graphql';

import GraphQLDate from 'graphql-date';

const events = new GraphQLObjectType({
    name: 'events',
    description: 'This represent an Event',
    fields: () => {
        return {
            id: {
                type: GraphQLID,
                resolve(event) {
                    return event.id;
                }
            },
            start: {
                type: GraphQLDate,
                resolve(event) {
                    return event.start;
                }
            }
        };
    }
});

the problem is that in my project with typescript when run server I get this message:

Error: events.start field type must be Output Type but got: undefined.

Source: (StackOverflow)

Graphql mutation for a column of type UUID[]

I'm using a postgraphql autogenerated mutation to create a row with graphql in a in a postgres table that has a column of datatype UUID[].

However, there doesn't seem to be a way to save this UUID[] data with graphql? Is this a datatype that graphql doesn't account for or am I wrongly forming the array?

When I go to create the row in graphiql:

mutation {
  createJob(
    input: {
      user_ids: ["5b7323ac-e235-4edb-bbf9-97495d9a42a1"], 
      instructions: "Job Instructions", 
      publishedDate: "2017-06-07"}
   }
 )
}

I get the following error:

"message": "column \"user_ids\" is of type uuid[] but expression is of type text[]"

Is a UUID technically not stored like text? I've tried different ways of forming the the UUID array but nothing seems to work


Source: (StackOverflow)

Postgraphql on Separate Heroku Port for Security?

I'd like to take a stab at using postgraphql for my Heroku app. I understand that I can use it either with the CLI or as middleware, but since I can't use the CLI with Heroku, I'm using the middleware to spawn an express app that acts as the graphQL server. Now, I'm trying to determine the best way to secure the server so it's only available to my separate, main express app to query from.

The best I've come up with is to run 2 different express apps on the same node instance. The main app uses the port assigned by Heroku so it can be accessed publicly, while the graphQL server uses a different port that I can query from the main app using localhost.

Is this enough to secure the graphQL server? AFAIK the graphQL port can't be publicly accessed since it's not the one assigned by Heroku. But my main app can still access it locally which is perfect.

Is there another way to secure the graphQL server? Maybe through authentication? Are there any disadvantages to my current method of using an unexposed Heroku port?

Here's the code that sets up the 2 different express apps on a single node instance so you can better understand what I'm doing:

const app = require('express')();
const graphQL = require('express')();
const postgraphql = require('postgraphql').postgraphql
// Use the port assigned by Heroku
const port = parseInt(process.env.PORT, 10) || 3000;
// graphQL will use a port 1 away
const graphQLPort = port + ((port < 65536) ? 1 : -1);

// Connect postgraphql to database using connection string
graphQL.use(postgraphql({connectionString: process.env.PGURI}));
// Spawn the graphQL server
graphQL.listen(graphQLPort, () => console.log(`GraphQL server listening on port ${graphQLPort}!`));

// Setup the main app here
// app.use(someMiddleware);

// Spawn the main app server
app.listen(port, () => console.log(`App server listening on port ${port}!`));

// Now I can make requests from the main app to the graphQL server
request(`http://localhost:${graphQLPort}/graphiql`, (err, res, body) => {
  console.log('error:', err);
  console.log('statusCode:', res && res.statusCode);
  console.log('body:', body);
});

Source: (StackOverflow)

Data is not storing using hibernate in multiple tables in PostgreSQL

I am new to hibernate. I am trying to store data using hibernate but it didn't go through. I can not find data in account table in database.

I found somewhere that I need to deal with cascade. I'm not sure how to implement that.

Thanks for the help.

Console Output

Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')

Controller Code to Store data

Address address = new Address();
//setting address properties.
Company newCompany = new Company();
address.setCompany(newCompany); 
addressDao.saveAddress(address);

Address.java

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name="id")
private long id;

private String type;

@Column(name = "street")
private String street;

@Column(name = "city")
private String city;

@Column(name = "zipcode")
private String zipcode;

@Column(name = "country")
private String country;

@ManyToOne(cascade=CascadeType.MERGE)
private User user;

@ManyToOne(cascade=CascadeType.MERGE)
private Company company;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getStreet() {
    return street;
}

public void setStreet(String street) {
    this.street = street;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getZipcode() {
    return zipcode;
}

public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public Company getCompany() {
    return company;
}

public void setCompany(Company company) {
    this.company = company;
}

Company.java

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int companyId;

@OneToMany(mappedBy="company", cascade=CascadeType.MERGE)
List<Address> address;

public Company()
{

}

public int getCompanyId() {
    return companyId;
}

public void setCompanyId(int companyId) {
    this.companyId = companyId;
}

public List<Address> getAddress() {
    return address;
}

public void setAddress(List<Address> address) {
    this.address = address;
}

Source: (StackOverflow)

Confusion with Relay Jwt Mutation for Authentication in PostgraphQL

OK, my humble apologies ... I am new to Relay and I am having a real problem getting my head around how to handle authentication with Postgraphql. PostgraphQl generates my graphql endpoint automatically from my postgres schema which works brilliantly, however I am struggling to work out how to handle auth.

I have an authenticate mutation which generates a jwt from a username and password. All that this mutation provides is a jwt token which is made up of the id of the authenticated user and the role.

My login page runs the mutation - the mutation requires no auth header. I then want to add an auth header with the jwt once the jwt is returned. I cannot see how to do this in relay at all as there is nothing in the local graphe at this point. Once I have the jwt all other queries will have the auth header set. I just cannot find any way to get the jwt as everytime i try to run the mutation, the props in input_0 are not set which I presume is because there is no node in the local graph.

here is my jwt.js (which is the mutation)

export default class JwtMutation extends Relay.Mutation {

  getMutation() {
    console.log("email:" + this.props.email + " / " + this.props.password );
    return Relay.QL`mutation{ authenticate }`;
  }

 getVariables() {
  return {
    email: this.props.email,
    password: this.props.password, 
  }
}
 getFragment() {
  return {
    jwtToken,
  }
 }

  getFatQuery() {
    return Relay.QL`
      fragment on AuthenticatePayload {
          jwtToken,
      }
    `;
  }
  getConfigs() {
    return [{
      type: 'REQUIRED_CHILDREN',
      children: [Relay.QL`
        fragment on AuthenticatePayload {
          jwtToken,
        }
      `]
    }];
  }
}

and my handlesubmit in login.js:

 handleSubmit = (event) => {
    event.preventDefault();

    let checkemail = this.state.loginName;
    let checkpassword = this.state.password;

    Relay.Store.commitUpdate(new JWTMutation({
      email: checkemail,
      password: checkpassword,
    }),
    { onFailure: (transaction) => {
          console.log('login failed');
          console.log(transaction.getError().source);
          const errorMessage = transaction.getError().source.errors[0].message;
    },
      onSuccess: (response) => {  
 // go ahead and store the jwt to local storage to be read and added to relay query header
      }
    }
    );
  };

Source: (StackOverflow)

Not allowed to secure GraphQL endpoint with JWT token

I'm running an express server and just put up JWT protection on my endpoints. I was testing out my /graphql endpoint and I am receiving a 403 Not allowed to provide a JWT token error. My other endpoints work fine, so I don't believe it is an issue with the JWT signing or verification. Any ideas?

var jwt = require('express-jwt');

var app = express();

var jwtCheck = jwt({
   secret: new Buffer(config.secret, 'base64'),
   audience: aud,
   issuer: iss
});

// enforce on all endpoints
app.use(jwtCheck);

app.use('/', postgraphql(config.db_string, config.db_schema, {
    development: true,
    log: true,
    secret: config.secret,
    graphiql: true,
}));

Postman Request landing on a vanilla graphql endpoint


Source: (StackOverflow)