• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React form library for Relay and Apollo

logo
GitHub Repo stars npm GitHub contributors NPM

periqles

Painless forms for GraphQL.
Demo β†’

Periqles is a React component library for Relay and Apollo that makes it easy to collect user input.

Periqles abstracts away the dirty work of form creation β€” with override switches built in for the design-conscious developer β€” so you can be free to focus on business logic. Given the name of a GraphQL mutation, periqles introspects the project's schema and intuits a form to match it. No need to waste time debugging React state management or fussing with flexbox β€” just drop in a tag and go on with your life.

β€œHaving knowledge but lacking the power to express it clearly is no better than never having any ideas at all.”
-- Pericles

screenshot of periqles form
Table of Contents
  1. Getting Started
  2. Usage
  3. Contributing
  4. License
  5. Maintainers
  6. Built with:

Getting Started

To add a <PeriqlesForm /> to your Apollo or Relay client, follow these steps.

Prerequisites

  • React (v. 16.8.0 and up)
    npm install react

Installation

  1. Install periqles from the terminal.
    npm install periqles
    
  2. Import PeriqlesForm into your frontend.
    // MyReactComponent.jsx
    import PeriqlesForm from 'periqles';
    

Server

Periqles relies on introspection queries to intuit the optimal form UI from your project's GraphQL schema. These queries will hit your server in the form of POST requests to /graphql. To use periqles, you must expose your schema at that /graphql endpoint.

In our demo, we use the client-agnostic express-graphql package to spin up a server in Node for our GraphQL API. See the documentation here and our code here. Apollo projects may use the Apollo Server without problems.

//server.js

const express = require('express');
const {graphqlHTTP}  = require('express-graphql');
const app = express();
const {schema} = require('./data/schema/index.js');

app.post(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    pretty: true,   // pretty-print JSON responses
  }),
);

If you are not using the /graphql endpoint to serve your API, options include configuring your server to redirect requests to /graphql to the correct endpoint or using a build tool like Webpack to proxy requests to /graphql to the correct address.

Schema

Currently, the introspection query used by periqles expects to find named input types on the schema. I.e., if you tell a <PeriqlesForm /> to generate a UI for your AddUser mutation, it will query your schema for a type called AddUserInput. Then it will render an input element for each input field listed on the AddUserInput type.

This means that periqles can successfully introspect this mutation:

#schema.graphql

type Mutation {
  addUser(input: AddUserInput!): AddUserPayload
}

# The mutation input is named and defined separately from the mutation.
input AddUserInput {
  username: String!
  password: String!
  email: String!
  gender: GenderEnum!
  pizzaTopping: PizzaToppingEnum!
  age: Int!
}

... but trying to introspect this mutation will cause your GraphQL server to throw back a 400 Bad Request error:

#schema.graphql

# The mutation input is not named and is defined in-line.
type Mutation {
  addUser(input: {
    username: String!
    password: String!
    email: String!
    gender: GenderEnum!
    pizzaTopping: PizzaToppingEnum!
    age: Int!
  }!): AddUserPayload
}

This is a high-priority area of improvement for us. We welcome PRs and other contributions.


Usage

<PeriqlesForm /> takes a number of props, including optional props to override its default logic for more fine-grained control over the apperance and composition of the form, the data sent to the API on submit, and state-management behavior.

PeriqlesForm Props

These are the props available to all clients. See below for more usage information specific to your client.

  • mutationName: string (required) β€” The name of a mutation as it appears on your GraphQL schema, e.g. 'AddUser' or 'AddUserMutation'.

    • If this is the only prop provided, periqles will render a form with default HTML intuited based on the name and scalar data type of each input field. E.g., an input field of type 'String' will result in <input type="text">. If the name of the input field appears in periqles' dictionary of common input fields, it will render a more specifically appropriate element. For example, a string-type field with the name 'password' will result in <input type="password">, and a field named 'mobile' will result in <input type="tel">.
  • specifications: object (optional) β€” If you wish to control the HTML or state management of a particular field, provide the instructions here. Periqles will fall back to its default logic for any fields or details not specified here.

    • header: string (optional) β€” If you wish to put a header on your form, e.g. "Sign up!", pass it here.
    • fields: object (optional) β€” Each key on fields should correspond to the name of an input field exactly as it appears on the schema. (E.g., based on the schema example above, 'pizzaTopping' is a valid key to use.) You can override defaults for as many or as few fields as you wish.
      • element: string (optional) β€” The HTML element you wish to use for this field, e.g. 'textarea', 'radio', 'datetime', etc.
      • label: string or element (optional) β€” The text, HTML, or JSX you wish to appear as a label for this field.
      • options: array (optional) β€” Whether or not this field is listed as an enumerated type on the schema, you may constrain valid user input on the frontend by using 'select' or 'radio' for the element field and providing a list of options here.
        • option: object (optional) β€” Specifies an option for this dropdown or group of radio buttons.
          • label: string or element (required) β€” The label you wish to appear for this option.
          • value: string or number (required) β€” The value to be submitted to the API.
      • render: function(params: {formState, setFormState, handleChange}) (optional) β€” If you wish to completely circumvent periqles' logic for rendering input fields, you may provide your own functional component here. The component you specify will completely replace the field <PeriqlesForm /> would have otherwise rendered. Parameters:
        • formState: object (optional) β€” The name and current value of each input field as key-value pairs.
        • setFormState: function(newFormState) (optional) β€” A React setState hook. Overwrites the entirety of formState with whatever is passed in.
        • handleChange: function(Event) (optional) β€” Destructures the input field's name and value off event.target to pass them as arguments to setFormState.
      • src: string (optional) β€” When element is 'img', the URL to use for the src attribute.
      • min: number (optional) β€” When element is 'range,' the number to use for the min attribute.
      • max: number (optional) β€” When element is 'range,' the number to use for the max attribute.
  • args: object (optional) β€” If there are any variables that you want to submit as input for the mutation but don't want to render as elements on the form, pass them here as key-value pairs. Example use cases include client-side authentication information or the clientMutationId in Relay. E.g.: const args = {userId: '001', clientMutationId: ${mutationId++}}. Fields listed here will be excluded from the rendered form but included on the mutation when the form is submitted.

  • callbacks: object (optional) β€” Developer-defined functions to be invoked when the form is submitted.

    • onSuccess: function(response) (optional) β€” Invoked if the mutation is successfully submitted to the API. In our demo (Relay, Apollo), we use onSuccess to trigger a very simple re-fetch and re-render of a component which displays <PeriqlesForm />'s output.
    • onFailure: function(error) (optional) β€” Invoked if the mutation fails to fire or the API sends back an error message. Use this to display meaningful error messages to the user.

Validation

Currently, periqles is able to validate input fields listed as non-null and of type string on the GraphQL schema. It will prevent the user from submitting the form if required text fields are left blank, including enumerated fields (represented by dropdowns or radio buttons) that are of type string.

This is high-priority area of improvement for us. If you have specific needs around validation, please open an issue or submit a PR.


Relay

In addition to the optional and required props listed above, <PeriqlesForm /> requires the following props when used in a Relay client:

  • environment: RelayEnvironment (required) β€” Your client's RelayEnvironment instance; necessary to send a mutation.
  • mutationGQL: GraphQLTaggedNode (required) β€” Your mutation, formatted as a tagged template literal using the graphql tag imported from react-relay. (NOT the version provided by graphql-tag.)

<PeriqlesForm /> uses the commitMutation function imported from Relay to fire off mutations when the form is submitted. If you pass an onSuccess and/or an onFailure callback on the callbacks prop, they will be invoked by commitMutation's onCompleted and onError callbacks, respectively.

CommitMutation takes additional callback parameters that are not currently included on <PeriqlesForm />'s callbacks prop, namely updater, optimisticResponse, optimisticUpdater, configs, and cacheConfigs. We plan to support these callbacks soon. If this is a high priority for your use case, please let us know by opening an issue, or submit a PR.

Here is a basic example of how to use <PeriqlesForm /> in Relay:

// MyComponent.jsx

import React, {useState} from 'react';
import {graphql} from 'react-relay';
import PeriqlesForm from 'periqles';

const ADD_USER =  graphql`
  mutation UserProfile_AddUserMutation($input: AddUserInput!) {
    addUser(input: $input) {
      username
      password
      email
      gender
      pizzaTopping
      age
    }
  }`;

const MyComponent = ({relay}) => {
  return (<div>
     <h1>Sign Up</h1>
     <PeriqlesForm
      mutationName={'AddUser'}
      mutationGQL={ADD_USER}
      environment={relay.environment}
     />
  </div>);
};

Full Code Sample


Apollo

In addition to the optional and required props listed above, <PeriqlesForm /> requires one additional prop when used in an Apollo client:

  • useMutation: function (required) β€” Your custom mutation hook, built using the useMutation hook imported from @apollo/client.

Here is a basic example of how to use <PeriqlesForm /> in Apollo:

// MyComponent.jsx

import React from 'react';
import { gql, useMutation } from '@apollo/client';
import PeriqlesForm from 'periqles';

const Signup = () => {
  const ADD_USER = gql`
    mutation AddUser($input: AddUserInput!){
      addUser(input: $input){
          username
          password
          email
          gender
          pizzaTopping
          age
        }
    }`;

  const [addUser, response] = useMutation(ADD_USER);

  return (<div>
     <h1>Sign Up</h1>
     <PeriqlesForm
      mutationName={'AddUser'}
      useMutation={addUser}
     />
  </div>);
};

Full Code Sample


Styles

Periqles comes with its own basic stylesheet, but it also attaches class names to each of its HTML elements that you can target in CSS for additional styling. We've tried to keep our default styles in that sweet spot between "enough to be presentable" and "adaptable to any design scheme." If you think we should provide more or less CSS, give us a shout in the issues.

Each element has two class names which follow this format:

  • "periqles-[element type]": e.g., 'periqles-textarea', 'periqles-radio-option'
  • "[field name]-[element type]": e.g., 'biography-textarea', 'gender-radio-option'

Contributing

If you would like to contribute to periqles, please fork this repo. Commit your changes to a well-named feature branch then open a pull request. We appreciate your contributions to this open-source project!

License

Distributed under the MIT License. See LICENSE for more information.

Maintainers

Built with:

More Repositories

1

sapling

Sapling - A convenient way to traverse your React app in VS Code
JavaScript
489
star
2

Kafka-Sprout

πŸš€ Web GUI for Kafka Cluster Management
Java
429
star
3

GraphQuill

Real-time GraphQL API Exploration in VS Code
TypeScript
395
star
4

protographql

ProtoGraphQL is a prototyping tool that empowers developers to build and visualize GraphQL schemas and queries without writing any code.
JavaScript
360
star
5

seeql

see your database in a new way
TypeScript
344
star
6

Realize

A React component tree visualizer
JavaScript
327
star
7

Allok8

⚑️A pretty swell Kubernetes visualization tool
JavaScript
273
star
8

ReactRTC

NPM package that simplifies set-up of WebRTC as importable React components
JavaScript
270
star
9

svend3r

Interactive plug and play charting library for Svelte
JavaScript
267
star
10

aether

All-in-One Memory Leak Testing Solution
JavaScript
250
star
11

Yodelay

Your preferred gRPC endpoint testing tool. Making sure your outbound πŸ—£οΈ β€˜yodelay’ returns the β€˜IiiOoo’ πŸ“£ that you expect
TypeScript
228
star
12

ReactRPC

Full feature integration library for gRPC-Web into React
JavaScript
224
star
13

atomos

Atomos is an open source dev tool for Recoil that provides real-time visualization of the component tree and atom-selector relationships to facilitate debugging of a React application.
JavaScript
218
star
14

Dockter

A low-overhead, open-source Docker log management tool
TypeScript
217
star
15

svelte-sight

A Svelte dev tool for visualizing component hierarchy, state, and props of your application
Svelte
215
star
16

KUR8

A visual overview of Kubernetes architecture and Prometheus metrics
JavaScript
213
star
17

OpticQL

Developer tool focused on streamlining the performance testing and optimization of GraphQL API
JavaScript
212
star
18

connext-js

A middleware and route handling solution for Next.js.
JavaScript
210
star
19

hypnos

The best way to test GraphQL calls to RESTful APIs.
JavaScript
205
star
20

Equa11y

A stream-lined command line tool for developers to easily run accessibility testing locally through axe-core and puppeteer.
TypeScript
204
star
21

preducks

React/Redux/Typescript Application Prototyping & Smart Boilerplate Generation Tool
TypeScript
199
star
22

drawql

an OSS tool for designing a graphql endpoint in Apollo
CSS
195
star
23

kubermetrics

JavaScript
194
star
24

TotalRecoilJS

TotalRecoilJS is a tool created to help developers visualize/debug and track their Recoil state via a Chrome extension.
JavaScript
193
star
25

Horus

🎯 A gRPC-Node Distributed Tracing and Monitoring Tool.
JavaScript
187
star
26

PostQL

Web app to visualize your GraphQL metrics and provide historical analytics
TypeScript
186
star
27

Ahoy

Ahoy! is a GUI tool for DevOps engineers which distills the many functions of Helm into a user-friendly interface.
JavaScript
183
star
28

battletest

A CLI module for npm that auto-generates tests based on user specified parameters.
JavaScript
183
star
29

Deno-Redlock

Deno's first lightweight, secure distributed lock manager utilizing the Redlock algorithm
TypeScript
182
star
30

ReactMonitor

Quickly visualize React's component tree and its performance
JavaScript
181
star
31

Osiris

An Electron based desktop application for generating components, building pages, and storing them in a UI library.
JavaScript
177
star
32

protostar-relay

Open-source iteration of the official Relay devtool.
JavaScript
171
star
33

TorchQL

A tool to quickly generate GraphQL schemas and resolvers from a relational database
JavaScript
171
star
34

trydent

testing tamed
TypeScript
170
star
35

genesisQL

rapid schema-prototyping tool for GraphQL applications
JavaScript
169
star
36

FilamentQL

GraphQL query and caching solution
JavaScript
168
star
37

GatsbyHub

Access everything Gatsby has to offer without ever leaving Visual Studio Code. This VSCode Extension allows you to generate a new Gatsby site using a starter, browse Gatsby plugins, and develop a server all with a click of a button.
TypeScript
163
star
38

aditum

Accessibility components for managing focus in React SPAs
JavaScript
162
star
39

watchmo

JavaScript
162
star
40

react-chronoscope

Developer tool to monitor React performance
JavaScript
162
star
41

navigate

A Kubernetes cluster visualizer for DevOps engineers - network policies, aggregated scheduler logs, deployments and pods before your cluster is running!
TypeScript
161
star
42

TrunQ

NPM package for easy client and/or server side graphQL caching.
JavaScript
160
star
43

onyx

Onyx is authentication middleware for Deno, inspired by Passport.js
TypeScript
159
star
44

BACE

JavaScript
159
star
45

MASH

Kafka visualizer and management suite
TypeScript
158
star
46

portara

Portara directive is a rate limiter / throttler for GraphQL
TypeScript
158
star
47

irisql

GraphQL prototyping tool to quickly mock-up Node API's and visualize where you can query from.
JavaScript
158
star
48

Interspect

An API mocking tool for testing data interoperability between microservices and secure HTTP endpoints
JavaScript
157
star
49

SMEE

JavaScript
154
star
50

ChaosQoaLa

Chaos Engineering meets GraphQL
JavaScript
153
star
51

VaaS

Modular Kubernetes Management System with OpenFaaS Support
TypeScript
153
star
52

tropicRPC

A VS Code extension that provides gRPC API endpoint testing.
TypeScript
153
star
53

dashport

Local and OAuth authentication middleware for Deno
TypeScript
151
star
54

anagraphql

JavaScript
151
star
55

Trinity

A VSCode extension for Cypher and Neo4j
TypeScript
150
star
56

DockerLocal

DockerLocal is a GUI application that allows you to keep an up-to-date version of the docker compose file for interconnected repositories while doing development work on a single repository.
TypeScript
150
star
57

giraffeQL

πŸ¦’ Developer tool to visualize relational databases and export schemas for GraphQL API's.
JavaScript
147
star
58

ProtoCAD

ProtoCAD is a prototyping tool that allows developers to build UI component tree structure based on GraphQL query results.
TypeScript
146
star
59

Trace

A lightweight GraphQL query performance monitoring GUI with real-time, resolver-level performance tracing metrics and error logging.
TypeScript
146
star
60

StratosDB

β˜„οΈ ☁️ An All-in-One GUI for Cloud SQL that can help users design and test their AWS RDS Instances
TypeScript
145
star
61

snAppy

snAppy is a VS Code extension coupled with an interactive view to support your React front-end delivery.
TypeScript
144
star
62

synapse

Realtime API Library
TypeScript
144
star
63

SpectiQL

GraphQL query, mutation, subscription test generator
JavaScript
143
star
64

starfleet

Command line tool to generate GraphQL services from Mongoose schemas with full CRUD functionality and deploy them to the cloud
JavaScript
143
star
65

pelican

Automated GUI canary testing for your kubernetes clusters
JavaScript
140
star
66

ProtoNative

A React Native prototyping tool for developers.
TypeScript
140
star
67

reactFLO

A Chrome DevTool built for developers to visualize the flow of state throughout their application.
TypeScript
140
star
68

ReactionTime

ReactionTime provides a simpler way to write tests for React's Experimental Concurrent Mode.
TypeScript
140
star
69

DacheQL

GraphQL caching tool
JavaScript
139
star
70

KuberOptic

An Electron app for developers to visualize their Kubernetes clusters in real-time
TypeScript
137
star
71

sono.land

Real-time Communication Library for Deno (WebSockets & WebRTC)
TypeScript
137
star
72

KubeScrape

KubeScrape: An open-source dev tool that provides an intuitive way to view the health, structure, and live metrics of your Kubernetes cluster
JavaScript
136
star
73

LucidQL

A developer tool and visualizer that generates a GraphQL schema from an established relational database.
JavaScript
135
star
74

Hookd

A cli tool and visualizer for converting React class components to functional components with hooks.
TypeScript
135
star
75

kr8s

Docker/Kubernetes Visualization Tool
JavaScript
133
star
76

Svelcro

Svelte DevTool with a focus on rendering
JavaScript
133
star
77

KnightOwl

An npm package of GraphQL middleware to protect you from malicious queries.
JavaScript
133
star
78

Palaemon

Palaemon is an open-source developer tool for monitoring health and resource metrics of Kubernetes clusters and analyzing Out of Memory (OOMKill) errors
TypeScript
133
star
79

SvelTable

Feature rich data table component.
Svelte
132
star
80

Ekkremis

A periscopic view into pending Kubernetes pods
TypeScript
132
star
81

kQ

TypeScript
131
star
82

fflow

fflow is an easy-to-use open-source tool for all developers to create their React application.
JavaScript
127
star
83

KlusterView

Get instant insights on your Kubernetes clusters with our lightweight, plug-and-play performance monitoring tool
TypeScript
125
star
84

Aqls-server

An intelligent full-stack GraphQL subscription and analytics module. Server-side analytics processing, self-auditing router, and resolver plugins.
JavaScript
123
star
85

kondo

JavaScript
123
star
86

ThermaKube

A web application that monitors the health and performance of Kubernetes clusters with support for AWS EKS deployments
JavaScript
120
star
87

arteMetrics

Creating performance monitors for Apollo implementations of graphQL.
JavaScript
118
star
88

QLens

QLens is an electron app which dynamically generates GraphQL Schemas and Mongo Schema visualization. QLens significantly cuts development time by automating the formation of their GraphQL schemas based on information fetched from their non-relational database.
JavaScript
118
star
89

firecomm

A complete framework for gRPC-node.
JavaScript
117
star
90

Kafkasocks

JavaScript
114
star
91

ReaPer

Dev tool to analyze the performance of user interface and single-page applications based on the React frontend library
JavaScript
114
star
92

dangoDB

A MongoDB ODM for Deno
TypeScript
111
star
93

AtomicKafka

JavaScript
110
star
94

Bedrock

A modular authentication library for Deno.
TypeScript
110
star
95

Docklight

Metrics for your Docker containers
TypeScript
109
star
96

Neptune

A light-weight, simple, and straightforward learning tool for your Kubernetes cluster
JavaScript
109
star
97

ArtemisQL

ArtemisQL is a GraphQL migration tool and database visualizer that empowers developers to build and implement GraphQL with ease.
TypeScript
108
star
98

shipm8

JavaScript
108
star
99

ReacTree

ReacTree - VS Code extension that generates a hierarchy tree of React components with each node listing the passed down props, indicating whether it's connected the Redux store, and guiding you to the associated file with the click of a button
TypeScript
107
star
100

reactron

Reactron is a React component visualizer that allows you to traverse an app's fiber tree and render components individually.
JavaScript
105
star