Introducing PostGraphile: Your Irresistible Pathway into the World of GraphQL | Sameer Kumar | October 2023

Introduction:

Preparing the database for your PostGraphile setup is simple. Create a schema if you need access control to certain tables and add necessary foreign keys to connect them. All you need is a valid database URL. To create a custom field, you can use database-level functions or write a resolver manually. PostGraphile also allows you to add descriptions to fields, control visibility of fields or tables, and implement access control using Postgres roles and schemas. Filtering records is supported natively, and you can enhance it with a connection filter plugin. Postgraphile optimizes your query conversion from GQL to SQL, eliminating the N+1 problem.

Full Article: Introducing PostGraphile: Your Irresistible Pathway into the World of GraphQL | Sameer Kumar | October 2023

Preparing the Database

In order to set up the database for PostGraphile, follow these simple steps:

  1. Create a basic Postgres setup without any additional steps.
  2. If you need access control to certain tables, create a schema explicitly.
  3. Add necessary foreign keys to connect various tables.
  4. Ensure you have a valid database URL for PostGraphile initialization.

Creating a Custom Field

Often, you may need a composite or computed field in your response object. Here are two ways to achieve this:

1. Use Database-Level Functions

This method is the fastest and most optimized as the code resides directly in the database. To create a custom field using this method, open the database console and run the following command:

CREATE OR REPLACE FUNCTION users_fullname(users users) RETURNS text AS
$$SELECT CONCAT(users.first_name, ' ', users.last_name)$$
LANGUAGE sql STABLE;

Notice the naming format for the function. It should be “tableName_fieldName”, allowing PostGraphile to automatically connect it as the resolver for that specific field. You can keep it as a database migration script or use it according to your needs.

2. Write Resolver Manually

In cases where custom functionalities are more complex, you can define them cleanly in the PostGraphile system. For example, if we want to create a fullName field, we can create it as an extension in a separate file and import it into the main file where the app is initialized.

Here’s an example of a custom resolver defined in fullname.js:

const { makeExtendSchemaPlugin, gql } = require("graphile-utils");

const FullNamePlugin = makeExtendSchemaPlugin({
  typeDefs: gql`extend type User {fullName: String}`,
  resolvers: {
    User: {
      fullName: (user, args, context, resolveInfo) => {
        return `${user.firstName} ${user.lastName}`;
      },
    },
  },
});

module.exports = FullNamePlugin;

To use this custom resolver, import it into the main file as shown below:

const FullNamePlugin = require("./fullname");

const postgraphileOptions = {
  ...,
  appendPlugins: [FullNamePlugin],
  ...
}

Once you’ve completed these steps, your custom field and resolver are ready to be used in the application.

Querying Custom Fields in PostGraphile

Querying custom fields in PostGraphile is straightforward. Simply include the desired field in your GraphQL query. For example:

query {
  user(id: 1) {
    id
    email
    name
  }
}

Adding a Description to Fields in GraphQL Explorer

To add a description to a field in the GraphQL Explorer, you can simply add a comment to the corresponding column in the SQL database. For example:

-- Add a description for the bpm field
comment on column tracks.bpm is E'Beats per Minute...';

After adding the comment, the description will be available in the GraphQL Explorer.

Control Visibility/Modification of Fields or Tables

PostGraphile provides a way to control the visibility or modification of fields and tables using magic comments. Here are a few examples:

-- Mark the users table as read-only
comment on table users is E'@omit create, update, delete';

-- Completely remove the version field from the tracks table in GraphQL
comment on column tracks.version is E'@omit read';

By using these magic comments, you can instruct PostGraphile to exclude specific fields or tables from GraphQL access.

Access Control to Records

PostGraphile utilizes Postgres roles and schemas for security, allowing fine-tuned access control to records. Here is an example of simple authorization:

GRANT SELECT ON users TO app_users;
GRANT DELETE ON users TO app_admins;

Additionally, row-level security features can be used to further restrict access to specific rows in a table. Here is an example:

create policy user_policy_select on public.users for select to users
using (email = current_setting('current_user_email'));
alter table users enable row level security;

Filtering Records

PostGraphile supports filtering natively to a certain extent and can be enhanced with full relational operator support using a connection filter plugin. Here is an example of the syntax:

query {
  getOneUser {
    user(id: 1) {
      id
      email
      name
    }
  }
}

By using the connection filter plugin, you can apply more advanced filtering options to your queries.

Remember, these are just some of the features and functionalities that PostGraphile offers. For more information, refer to the PostGraphile documentation to further explore its capabilities.

Summary: Introducing PostGraphile: Your Irresistible Pathway into the World of GraphQL | Sameer Kumar | October 2023

Title: Optimizing PostGraphile: A Guide to Customization and Performance

Summary: Discover how to optimize and customize PostGraphile, a powerful tool for creating GraphQL APIs from your PostgreSQL database. Learn how to prepare the database, create custom fields, add descriptions, control visibility of fields and tables, implement access control, and optimize filtering performance.

Keywords: PostGraphile, PostgreSQL, GraphQL APIs, customization, performance optimization, database preparation, custom fields, field descriptions, visibility control, access control, filtering optimization.

The article provides a comprehensive guide on optimizing and customizing PostGraphile, a tool used to create GraphQL APIs. Learn about database preparation, creating custom fields, adding descriptions, controlling field visibility, implementing access control, and optimizing filtering performance for better overall performance. A must-read for developers looking to maximize the potential of PostGraphile.




PostGraphile – FAQs

PostGraphile – Frequently Asked Questions

What is PostGraphile?

PostGraphile is an open-source library that enables automatic GraphQL API generation for PostgreSQL databases. It provides a powerful and efficient way to query and manipulate data stored in a PostgreSQL database using GraphQL.

Why is it called “The Gateway Drug To GraphQL”?

PostGraphile is often referred to as “The Gateway Drug To GraphQL” because it simplifies the adoption of GraphQL by leveraging the existing PostgreSQL database schema. It allows developers to gradually transition from traditional REST APIs to GraphQL by providing automatic GraphQL API generation.

How does PostGraphile work?

PostGraphile analyzes the PostgreSQL database schema and generates a GraphQL API based on the schema. It automatically generates resolvers, types, and queries that correspond to the tables and columns in the database. This greatly reduces the amount of manual coding required to create a GraphQL API.

Is PostGraphile SEO friendly?

Yes, PostGraphile-generated GraphQL APIs are SEO friendly. Although GraphQL APIs are traditionally not as SEO friendly as REST APIs, PostGraphile provides built-in support for enabling search engine optimization. It helps generate optimized schema designs and enables query optimizations that enhance the performance of the API.

How can I make my PostGraphile API more attractive to humans?

To make your PostGraphile API more attractive to humans, you can use PostGraphile’s plugin system to add custom logic, authentication, and authorization. You can also leverage GraphQL’s declarative nature to create intuitive and easy-to-understand queries for clients. Additionally, you can implement user-friendly error handling and provide detailed documentation to enhance the overall developer experience.

Why is it important for an API to be easy to understand?

An API that is easy to understand is crucial for developers as it reduces the learning curve and enables faster and more efficient development. Easy-to-understand APIs also increase the developer’s productivity and satisfaction, as it becomes easier to navigate, comprehend, and use the API effectively. Clear and concise documentation is key to achieving an easy-to-understand API.

Can I use as many headings as possible in HTML?

While there is no strict limit on the number of headings you can use in HTML, it is generally recommended to follow a logical heading structure and avoid excessive heading levels. Using too many headings can make the content harder to navigate and understand for both humans and search engine crawlers. Aim for a balanced and meaningful hierarchy of headings that accurately represents the content’s structure.