This time we’ll learn how to use it by quickly building a GraphQL project.

Technology stack used in the project:

  • Typescript-a typed superset of JavaScript that compiles to pure JavaScript.
  • Node.js – a JavaScript runtime based on the Chrome V8 engine.
  • Graphql-api’s query language for the runtime to complete these queries using existing data.
  • Modern framework for GraphQL API in TypeGraphQL-node. js.

Project depend on

  • Node.js – can be downloaded here and version V12.6.3 is recommended

Project initialization

  • The terminal goes to the folder where the project is stored and creates the project:
$ mkdir tinylearn && cd tinylearn
Copy the code
  • Project initialization:
$ npm init -y
Copy the code
  • Open the project with an editor (I’m using VSCode) :

  • To install dependency packages, enter:
$NPM install [email protected] \
    [email protected] \
    [email protected] \
    [email protected]  \
    [email protected]
Copy the code
$NPM install -- save-dev@types /[email protected] \
    @types/[email protected] \
    [email protected] \
    [email protected]
Copy the code
  • Add files to the project root directorytinylearn/tsconfig.json:
{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "lib": [
      "es2018",
      "esnext.asynciterable"
    ],
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
Copy the code

Tsconfig. json is a Typescript configuration file that specifies the root file and compiler options required to compile the project.

Hello world

Now that we’ve done our prep work, let’s write some code.

  • createtinylearn/src/index.tsFile and write the relevant code:

index.ts:

console.log('Hello world! ');
Copy the code
  • Modify thepackage.json:
{
  "name": "tinylearn",

  ...

  "scripts": {
+ "start": "ts-node src"
- "test": "echo \"Error: no test specified\" && exit 1"},... }Copy the code
  • Run the following command to start the project:
$ npm start
Copy the code

The results are as follows:

Congratulations Hello World is running!

The introduction ofGraphQL

Now we’re going to write some logic.

  • Modify thesrc/index.tsTo:
import "reflect-metadata"
import { buildSchema, ObjectType, Field, ID, Resolver, Query } from "type-graphql";
import { ApolloServer } from "apollo-server";

@ObjectType(a)class Post {

  @Field(type= > ID)
  id: string;

  @Field()
  created: Date;

  @Field()
  content: string;
}

@Resolver(Post)
class PostResolver {

  @Query(returns= > [Post])
  async posts(): Promise<Post[]> {
    return [
      {
        id: "0",
        created: new Date(),
        content: 'Data query and access based on GraphQL API, "Hasura" received $9.9 million series A... '
      },
      {
        id: "1",
        created: new Date(),
        content: 'Why GraphQL is the future of apis'
      },
      {
        id: "2",
        created: new Date(),
        content: Netflix: Why did we bring GraphQL to the front-end architecture? '}}},]async function main() {

  try {

    const schema = await buildSchema({
      resolvers: [PostResolver],
      dateScalarMode: 'timestamp'
    });


    const server = new ApolloServer({
      schema,
      playground: true
    });

    const { url } = await server.listen(4444);

    console.log(`GraphQL Playground available at ${url}`);

  } catch (error) {
    console.error(error);
  }
}


main();
Copy the code
  • Run the project again:
$ npm start
Copy the code

Results:

Have some fun

Visit http://localhost:4444/: for your browser

Let’s start by clicking the SCHEMA button on the right:

Then type on the left:

It will have auto-complete, so typing should be easy.

Click the play button in the middle circle:

In fact, this page is like Postman. The left side can be seen as the configuration of the front-end request, the middle is the JSON returned by the server, and the right side can be seen as the API documentation of the backend.

Let’s change the parameters and send the request again:

The whole process is like defining a JSON graph (or schema) on the back end, and the front end pulls parts of the graph as needed.

Let’s review tinylearn/ SRC /index.ts again:

@ObjectType(a)class Post {

  @Field(type= > ID)
  id: string;

  @Field()
  created: Date;

  @Field()
  content: string;
}

@Resolver(Post)
class PostResolver {

  @Query(returns= > [Post])
  async posts(): Promise<Post[]> {
    return [
      {
        id: "0",
        created: new Date(),
        content: 'Data query and access based on GraphQL API, "Hasura" received $9.9 million series A... '
      },
      {
        id: "1",
        created: new Date(),
        content: 'Why GraphQL is the future of apis'
      },
      {
        id: "2",
        created: new Date(),
        content: Netflix: Why did we bring GraphQL to the front-end architecture? '}}},]Copy the code

Backend definition Schema:

The front-end initiates requests based on the requirements and the Schema:

The front-end gets the return value:

In addition, the JSON graph (schema) is a strict type system:

  • posts: [Posts!] !– Post array
  • id: ID!– String ID
  • created: Timestamp!– a timestamp
  • content: String!– string

Let’s check the type of the return value:

True, the return value is of the same type as in Schema:

Posts is an array of posts.

Id is the string ID. Created is a timestamp. Content is a string.

Is there anything new about GraphQL? Please leave me a message.

To be continued

You may still have a lot of questions, so take your time.

The next article “How To Access GraphQL with Flutter” will show you how to access the interface written in this chapter using Flutter (mobile hot). Get the front end running so we can get a fuller picture of GraphQL.

Flutter Demo:

The source code

The code address

tinylearn/src/index.ts:

import "reflect-metadata"
import { buildSchema, ObjectType, Field, ID, Resolver, Query } from "type-graphql";
import { ApolloServer } from "apollo-server";

@ObjectType(a)class Post {

  @Field(type= > ID)
  id: string;

  @Field()
  created: Date;

  @Field()
  content: string;
}

@Resolver(Post)
class PostResolver {

  @Query(returns= > [Post])
  async posts(): Promise<Post[]> {
    return [
      {
        id: "0",
        created: new Date(),
        content: 'Data query and access based on GraphQL API, "Hasura" received $9.9 million series A... '
      },
      {
        id: "1",
        created: new Date(),
        content: 'Why GraphQL is the future of apis'
      },
      {
        id: "2",
        created: new Date(),
        content: Netflix: Why did we bring GraphQL to the front-end architecture? '}}},]async function main() {

  try {

    const schema = await buildSchema({
      resolvers: [PostResolver],
      dateScalarMode: 'timestamp'
    });


    const server = new ApolloServer({
      schema,
      playground: true
    });

    const { url } = await server.listen(4444);

    console.log(`GraphQL Playground available at ${url}`);

  } catch (error) {
    console.error(error);
  }
}


main();
Copy the code

reference

  • GraphQL
  • TypeGraphQL
  • ApolloServer
  • tsconfig.json
  • package.json