All Projects → codica2 → Nextjs Graphql Sample

codica2 / Nextjs Graphql Sample

A simple app to demonstrate basic API functions built with REST and GraphQL

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to Nextjs Graphql Sample

Api Platform
Create REST and GraphQL APIs, scaffold Jamstack webapps, stream changes in real-time.
Stars: ✭ 7,144 (+24534.48%)
Mutual labels:  api, graphql, rest, nextjs
Json Serverless
Transform a JSON file into a serverless REST API in AWS cloud
Stars: ✭ 108 (+272.41%)
Mutual labels:  api, graphql, rest
Strapi
🚀 Open source Node.js Headless CMS to easily build customisable APIs
Stars: ✭ 41,786 (+143989.66%)
Mutual labels:  api, graphql, rest
Examples
Examples of Mock Service Worker usage with various frameworks and libraries.
Stars: ✭ 163 (+462.07%)
Mutual labels:  api, graphql, rest
Subzero Starter Kit
Starter Kit and tooling for authoring GraphQL/REST API backends with subZero
Stars: ✭ 136 (+368.97%)
Mutual labels:  api, graphql, rest
Vulcain
Fast and idiomatic client-driven REST APIs.
Stars: ✭ 3,190 (+10900%)
Mutual labels:  api, graphql, rest
Core
The server component of API Platform: hypermedia and GraphQL APIs in minutes
Stars: ✭ 2,004 (+6810.34%)
Mutual labels:  api, graphql, rest
Storefront Api
Storefront GraphQL API Gateway. Modular architecture. ElasticSearch included. Works great with Magento1, Magento2, Spree, OpenCart, Pimcore and custom backends
Stars: ✭ 180 (+520.69%)
Mutual labels:  api, graphql, rest
Requester
Powerful, modern HTTP/REST client built on top of the Requests library
Stars: ✭ 273 (+841.38%)
Mutual labels:  api, graphql, rest
Graphql2rest
GraphQL to REST converter: automatically generate a RESTful API from your existing GraphQL API
Stars: ✭ 181 (+524.14%)
Mutual labels:  api, graphql, rest
Crudl
CRUDL is a backend agnostic REST and GraphQL based admin interface
Stars: ✭ 438 (+1410.34%)
Mutual labels:  api, graphql, rest
Django Api Domains
A pragmatic styleguide for Django API Projects
Stars: ✭ 365 (+1158.62%)
Mutual labels:  api, graphql, rest
Just Api
💥 Test REST, GraphQL APIs
Stars: ✭ 768 (+2548.28%)
Mutual labels:  api, graphql, rest
Deno Drash
A REST microframework for Deno's HTTP server with zero 3rd party dependencies.
Stars: ✭ 795 (+2641.38%)
Mutual labels:  api, rest
Ngx Restangular
Restangular for Angular 2 and higher versions
Stars: ✭ 787 (+2613.79%)
Mutual labels:  api, rest
Goyave
🍐 Elegant Golang REST API Framework
Stars: ✭ 811 (+2696.55%)
Mutual labels:  api, rest
Graphiti
Stylish Graph APIs
Stars: ✭ 783 (+2600%)
Mutual labels:  api, graphql
Versionist
A plugin for versioning Rails based RESTful APIs.
Stars: ✭ 950 (+3175.86%)
Mutual labels:  api, rest
Apipie
Transform api declaration to js object for frontend. Inspired by VueRouter, koa-middleware and axios.
Stars: ✭ 29 (+0%)
Mutual labels:  api, rest
Django apistar
Django App to integrate API Star's routes and views into Django's ecossystem.
Stars: ✭ 25 (-13.79%)
Mutual labels:  api, rest

Next.js project example with TypeScript & GraphQl

Description

This is an example/boilerplate of a nextjs project using Typescript and Apollo.

The main idea behind the example is to show the best typescript and GraphQL usage by integration of the Apollo client and types generating using GraphQL Code Generator.

Moreover, for writing styles it suggests no less interesting approach with combining styled-components and styled-system Read more. 😃

In this example, Apollo is integrated by wrapping our pages with HOC. Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application.

Table of Contents

Usage

Install it and run:

npm install
npm run dev

# or

yarn
yarn dev

File structure

    .
    ├── ...
    ├── generated/             # generated graphql types
    ├── graphql/               # graphql queries and mutations splitted by entities
    ├── interfaces/            # custom ts interfaces
    ├── utils/                 # app utilities
    ├── pages/                 # next.js pages
    ├── server/                # custom server
    ├── views
    │   ├── components/        # components
    │   ├── layouts/           # application layouts
    │   ├── styled/            # styled components + styled system types
    │   └── ui/                # ui components(Button, Inputs, etc.)
    └── ...

Configuration

Also, this example is easily configurable. The main config file next.config.js is placed in the root. You can engage all the needed plugins there. Next-compose-plugins is used for composing all the plugins together, It provides a cleaner API for enabling and configuring plugins.

const withPlugins = require("next-compose-plugins");
const withTypescript = require("@zeit/next-typescript");
const withLess = require("@zeit/next-less");

module.exports = withPlugins(
  [
    // add a plugin without a configuration
    withTypescript,

    // add a plugin with specific configuration
    [
      withLess,
      {
        lessLoaderOptions: {
          javascriptEnabled: true
        }
      }
    ]
  ],
  nextConfig // next.js configuration
);

Making GraphQl queries and mutations

In order to make a GraphQL query or request, firstly we should describe the schemas, all of them should be placed in the graphql folder, we actually splitted them by entities for convenience of use.

Then we must generate typescript types read more. After this, you could use these generated components:

<LoginComponent>
{(<LoginMutation>, <LoginVariables>) => (
  ...code
)}
</LoginComponent>

Styling

This exapmle uses styled-components along with styled-system approach.

Styled-components is a CSS-in-JS library which allows you to write actual CSS code to style your components.

Styled-System provides you with a set of utilities that map props to your design system. It uses the concept of style functions. Each style function exposes its own set of props that style elements based on values defined in your design system theme. It has a rich API with functions for most CSS properties.

The Design Styled System theme object is intended to be a general purpose format for storing design system style values and scales:

const theme = {
  breakpoints: [32, 48, 64],
  space: [0, 4, 8, 16, 32, 64, 128, 256, 512],
  fontSizes: [12, 14, 16, 20, 24, 36, 48, 80, 96],
  fontWeights: [100, 200, 300, 400, 500, 600, 700, 800, 900],
  colors: {
    primary: "#000",
    secondary: "#ccc",
    ...
  },
   buttonSizes: {
    xs: `
      height: 16px;
      padding: 0 16px;
      font-size: 10px;
    `,
    sm: `
      height: 24px;
      padding: 0 24px;
      font-size: 13px;
    `,
    md: `
      height: 34px;
      padding: 0 34px;
      font-size: 14px;
      letter-spacing: 0.4px;
    `
  ...

Our styled components utilize what we call system props to apply a custom set of props to a component. We adopted this approach by creating seperate types like layout, typography, flexbox, and others. This means that every component is guaranteed to have the same API.

Here is an example of the common type, we use the compose utility to create custom type that each new component can use.

import * as SS from "styled-system";

// typescript type
export type CommonProps = SS.SpaceProps &
  SS.WidthProps &
  SS.HeightProps &
  SS.ColorProps &
  SS.FontSizeProps;

// common type
export default SS.compose(
  SS.space,
  SS.width,
  SS.height,
  SS.color,
  SS.fontSize
);

This is a component for styling headings, here we import our custom common and typography functions, moreover, we could extend it with our custom css styles. Also, we add some default styled-system props.

import styled, { StyledComponent } from "styled-components";
import { borders, BordersProps } from "styled-system";

import common, { CommonProps } from "./types/common";
import typography, { TypographyProps } from "./types/typography";

type Props = CommonProps & TypographyProps & BordersProps;

const Heading: StyledComponent<Props> = styled("h1")(
  { margin: "0 0 20px" },

  common,
  borders,
  typography
);

Heading.defaultProps = {
  fontSize: [2, 3, 4],
  fontWeight: 5,
  color: "primary"
};

Heading.displayName = "Heading";

export default Heading;

Eventually, we can easily reuse this styled component adding different props.

// (theme.fontSizes[4])
<Heading fontSize={4} />

// (theme.space[3])
<Heading m={2} />

// (theme.colors.blacks[0])
<Heading color="blacks.3" />

Features

GraphQL types

To generate GraphQL types out of GraphQL schemas we use GraphQL Code Generator, it takes all our GraphQL queries and mutations from graphql/**/* and generates typescript components into a generated/apolloComponents.tsx file, so after you could use it inside your components. In order to generate it run npm run generate or yarn generate command. You should regenerate types every time any graphql mutation or query changes ❗️

Protected routes

For catching authentication errors we use HOC, it makes an initial GraphQL query to get the authenticated. If there is no authenticated user it redirects to the login page.

export const withAuth = <T extends object>(
  C: React.ComponentClass<T> | React.FC
) => {
  return class AuthComponent extends React.Component<T> {
    static async getInitialProps({
      apolloClient,
      ...ctx
    }: NextContextWithApollo) {
      const response = await apolloClient.query<MeQuery>({ query: meQuery });
      if (!response || !response.data || !response.data.me) {
        redirect(ctx, "/login");

        return {
          me: null
        };
      }

      return {
        me: response.data.me
      };
    }

    render() {
      return <C {...this.props} />;
    }
  };
};

License

nextjs-graphql-sample is Copyright © 2015-2019 Codica. It is released under the MIT License.

About Codica

Codica logo

We love open source software! See our other projects or hire us to design, develop, and grow your product.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].