Kukuh  Pratama

Kukuh Pratama

1625626939

Sveltekit Crash Course - Svelte TypeScript - Getting started with Sveltekit Endpoints

I’ll show how to set up a project from scratch using the framework SvelteKit with Typescript. The main focus in this video is to explain Sveltekit endpoints and Typescript in combination with Svelte.

Support me by subscribing to this channel ❤️

Do you want to master #react, #gatsby, or #svelte fast? ⏩ 🚀 👩‍🚀

Find me somewhere below:

Website: https://www.weibenfalk.com
Udemy: https://www.udemy.com/user/thomas-928/
Linkedin: https://www.linkedin.com/in/thomas-weibenfalk-76356611/
Twitter: https://twitter.com/weibenfalk
Github: https://github.com/weibenfalk
FreeCodeCamp: https://www.freecodecamp.org/news/author/thomas-weibenfalk/
Dev.to: https://dev.to/weibenfalk

#svelte #typescript #sveltekit

What is GEEK

Buddha Community

Sveltekit Crash Course - Svelte TypeScript - Getting started with Sveltekit Endpoints
Shubham Ankit

Shubham Ankit

1657081614

How to Automate Excel with Python | Python Excel Tutorial (OpenPyXL)

How to Automate Excel with Python

In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation

What is OPENPYXL

Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.

Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.

Sheet: A sheet is a single page composed of cells for organizing data.

Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.

Row: A row is a horizontal line represented by a number (1,2, etc.).

Column: A column is a vertical line represented by a capital letter (A, B, etc.).

Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.

pip install openpyxl

CREATE A NEW WORKBOOK

We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook() which creates a new workbook.

from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method

ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position

#Renaming the sheet
ws.title = "Example"

#save the workbook
wb.save(filename = "example.xlsx")

READING DATA FROM WORKBOOK

We load the file using the function load_Workbook() which takes the filename as an argument. The file must be saved in the same working directory.

#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")

 

GETTING SHEETS FROM THE LOADED WORKBOOK

 

#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']

#getting a particular sheet
sheet1 = wb["sheet2"]

#getting sheet title
sheet1.title
result = 'sheet2'

#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'

 

ACCESSING CELLS AND CELL VALUES

 

#get a cell from the sheet
sheet1["A1"] <
  Cell 'Sheet1'.A1 >

  #get the cell value
ws["A1"].value 'Segment'

#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10

 

ITERATING THROUGH ROWS AND COLUMNS

 

#looping through each row and column
for x in range(1, 5):
  for y in range(1, 5):
  print(x, y, ws.cell(row = x, column = y)
    .value)

#getting the highest row number
ws.max_row
701

#getting the highest column number
ws.max_column
19

There are two functions for iterating through rows and columns.

Iter_rows() => returns the rows
Iter_cols() => returns the columns {
  min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.

Example:

#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
  for cell in row:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C3 >

  #iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
  for cell in col:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.C3 >

To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.


Example:

for row in ws.values:
  for value in row:
  print(value)

 

WRITING DATA TO AN EXCEL FILE

Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.

 

CREATING AND SAVING A NEW WORKBOOK

 

#creates a new workbook
wb = openpyxl.Workbook()

#saving the workbook
wb.save("new.xlsx")

 

ADDING AND REMOVING SHEETS

 

#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")

#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")

#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']

#deleting a sheet
del wb['sheet 0']

#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']

 

ADDING CELL VALUES

 

#checking the sheet value
ws['B2'].value
null

#adding value to cell
ws['B2'] = 367

#checking value
ws['B2'].value
367

 

ADDING FORMULAS

 

We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
 

For example:

import openpyxl
from openpyxl
import Workbook

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']

ws['A9'] = '=SUM(A2:A8)'

wb.save("new2.xlsx")

The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.

image

 

MERGE/UNMERGE CELLS

Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().

For example:
Merge cells

#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"

Adding the above code to the previous example will merge cells as below.

image

UNMERGE CELLS

 

#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')

The above code will unmerge cells from B2 to C9.

INSERTING AN IMAGE

To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.

Example:

import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3

ws.add_image(img, 'A3')

wb.save("new2.xlsx")

Result:

image

CREATING CHARTS

Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:

Example

import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series

wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active

values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")

Result
image


How to Automate Excel with Python with Video Tutorial

Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.

⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling

📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/ 
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial 
Subscribe: https://www.youtube.com/c/TechWithTim/featured 

#python 

Kukuh  Pratama

Kukuh Pratama

1625626939

Sveltekit Crash Course - Svelte TypeScript - Getting started with Sveltekit Endpoints

I’ll show how to set up a project from scratch using the framework SvelteKit with Typescript. The main focus in this video is to explain Sveltekit endpoints and Typescript in combination with Svelte.

Support me by subscribing to this channel ❤️

Do you want to master #react, #gatsby, or #svelte fast? ⏩ 🚀 👩‍🚀

Find me somewhere below:

Website: https://www.weibenfalk.com
Udemy: https://www.udemy.com/user/thomas-928/
Linkedin: https://www.linkedin.com/in/thomas-weibenfalk-76356611/
Twitter: https://twitter.com/weibenfalk
Github: https://github.com/weibenfalk
FreeCodeCamp: https://www.freecodecamp.org/news/author/thomas-weibenfalk/
Dev.to: https://dev.to/weibenfalk

#svelte #typescript #sveltekit

Build a GraphQL app in Node.js with TypeScript and graphql-request

In this article, you will build a full-stack app using GraphQL and Node.js in the backend. Meanwhile, our frontend will use the graphql-request library to perform network operations on our backend.

Why use graphql-request and TypeScript?

Whenever developers build a GraphQL server using Apollo, the library generates a “frontend” which looks like so:

Frontend Developed By GraphQL And Apollo

This interface allows users to make query or mutation requests to the server via code. However, let’s address the elephant in the room: it doesn’t look very user friendly. Since the frontend doesn’t feature any buttons or any helpful interface elements, it might be hard for many users to navigate around your app. Consequently, this shrinks your user base. So how do we solve this problem?

This is where graphql-request comes in. It is an open source library which lets users perform queries on a GraphQL server. It boasts the following features:

  • Lightweight — This library is just over 21 kilobytes minified, which ensures your app stays performant
  • Promise-based API — This brings in support for asynchronous applications
  • TypeScript support — graphql-request is one of many libraries which allows for TypeScript. One major advantage of Typescript is that it allows for stable and predictable code

For example, look at the following program:

let myNumber = 9; //here, myNumber is an integer
myNumber = 'hello'; //now it is a string.
myNumber = myNumber + 10; //even though we are adding a string to an integer,
//JavaScript won't return an error. In the real world, it might bring unexpected outputs.
//However, in Typescript, we can tell the compiler..
//what data types we need to choose.
let myNumber:number = 39; //tell TS that we want to declare an integer.
myNumber = 9+'hello'; //returns an error. Therefore, it's easier to debug the program
//this promises stability and security. 

In this article, we will build a full-stack app using GraphQL and TypeScript. Here, we will use the apollo-server-express package to build a backend server. Furthermore, for the frontend, we will use Next and graphql-request to consume our GraphQL API.

Building our server

Project initialization

To initialize a blank Node.js project, run these terminal commands:

mkdir graphql-ts-tutorial #create project folder 
cd graphql-ts-tutorial 
npm init -y #initialize the app

When that’s done, we now have to tell Node that we need to use TypeScript in our codebase:

#configure our Typescript:
npx tsc --init --rootDir app --outDir dist --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
mkdir app #our main code folder
mkdir dist #Typescript will use this folder to compile our program.

Next, install these dependencies:

#development dependencies. Will tell Node that we will use Typescript
npm install -d ts-node @types/node typescript @types/express nodemon
#Installing Apollo Server and its associated modules. Will help us build our GraphQL
#server
npm install apollo-server-express apollo-server-core express graphql

After this step, navigate to your app folder. Here, create the following files:

  • index.ts: Our main file. This will execute and run our Express GraphQL server
  • dataset.ts: This will serve as our database, which will be served to the client
  • Resolvers.ts: This module will handle user commands. We will learn about resolvers later in this article
  • Schema.ts: As the name suggests, this file will store the schematics needed to send data to the client

In the end, your folder structure should look like so:

Folder Structure

Creating our database

In this section, we will create a dummy database which will be used to send requested data. To do so, go to app/dataset.ts and write the following code:

let people: { id: number; name: string }[] = [
  { id: 1, name: "Cassie" },
  { id: 2, name: "Rue" },
  { id: 3, name: "Lexi" },
];
export default people;
  • First, we created an array of objects called people
  • This array will have two fields: id of type number, and name of type string

Defining our schema

Here, we will now create a schema for our GraphQL server.

To put it simply, a GraphQL schema is a description of the dataset that clients can request from an API. This concept is similar to that of the Mongoose library.
To build a schema, navigate to the app/Schema.ts file. There, write the following code:

import { gql } from "apollo-server-express"; //will create a schema
const Schema = gql`
  type Person {
    id: ID!
    name: String
  }
  #handle user commands
  type Query {
    getAllPeople: [Person] #will return multiple Person instances
    getPerson(id: Int): Person #has an argument of 'id` of type Integer.
  }
`;
export default Schema; 
//export this Schema so we can use it in our project

Let’s break down this code piece by piece:

  • The Schema variable contains our GraphQL schema
  • First, we created a Person schema. It will have two fields: id of type ID and name of type String
  • Later on, we instructed GraphQL that if the client runs the getAllPeople command, the server will return an array of Person objects
  • Furthermore, if the user uses the getPerson command, GraphQL will return a single Person instance

Creating resolvers

Now that we have coded our schema, our next step is to define our resolvers.
In simple terms, a resolver is a group of functions that generate response for a GraphQL query. In other words, a resolver serves as a GraphQL query handler.
In Resolvers.ts, write the following code:

import people from "./dataset"; //get all of the available data from our database.
const Resolvers = {
  Query: {
    getAllPeople: () => people, //if the user runs the getAllPeople command
    //if the user runs the getPerson command:
    getPerson: (_: any, args: any) => { 
      console.log(args);
      //get the object that contains the specified ID.
      return people.find((person) => person.id === args.id);
    },
  },
};
export default Resolvers;
  • Here, we created a Query object that handles all the incoming queries going to the server
  • If the user executes the getAllPeople command, the program will return all the objects present in our database
  • Moreover, the getPerson command requires an argument id. This will return a Person instance with the matching ID
  • In the end, we exported our resolver so that it could be linked with our app

Configuring our server

We’re almost done! Now that we have built both our schema and resolver, our next step is to link them together.

In index.js, write this block of code:

import { ApolloServer } from "apollo-server-express";
import Schema from "./Schema";
import Resolvers from "./Resolvers";
import express from "express";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import http from "http";

async function startApolloServer(schema: any, resolvers: any) {
  const app = express();
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    typeDefs: schema,
    resolvers,
    //tell Express to attach GraphQL functionality to the server
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  }) as any;
  await server.start(); //start the GraphQL server.
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve) //run the server on port 4000
  );
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
}
//in the end, run the server and pass in our Schema and Resolver.
startApolloServer(Schema, Resolvers);

Let’s test it out! To run the code, use this Bash command:

npx nodemon app/index.ts 

This will create a server at the localhost:4000/graphql URL.

Here, you can see your available schemas within the UI:

Available Schemas Within The UI

This means that our code works!

All of our GraphQL queries will go within the Operation panel. To see it in action, type this snippet within this box:

#make a query:
query {
  #get all of the people available in the server
  getAllPeople {
    #procure their IDs and names.
    id
    name
  }
}

To see the result, click on the Run button:

Run Button For Results

We can even search for a specific entity via the getPerson query:

query ($getPersonId: Int) { #the argument will be of type Integer
  getPerson(id: 1) {
    #get the person with the ID of 1
    name
    id
  }
}

Getperson Query

Creating mutations

In the GraphQL world, mutations are commands that perform side effects on the database. Common examples of this include:

  • Adding a user to the database — When a client signs up for a website, the user performs a mutation to save their data in their database
  • Editing or deleting an object — If a user modifies or removes data from a database, they are essentially creating a mutation on the server

To handle mutations, go to your Schema.ts module. Here, within the Schema variable, add the following lines of code:

const Schema = gql`
  #other code..
  type Mutation {
    #the addPerson commmand will accept an argument of type String.
    #it will return a 'Person' instance. 
    addPerson(name: String): Person
  }
`;

Our next step is to create a resolver to handle this mutation. To do so, within the Resolvers.ts file, add this block of code:

const Resolvers = {
  Query: {
    //..further code..
  },
  //code to add:
  //all our mutations go here.
  Mutation: {
    //create our mutation:
    addPerson: (_: any, args: any) => {
      const newPerson = {
        id: people.length + 1, //id field
        name: args.name, //name field
      };
      people.push(newPerson);
      return newPerson; //return the new object's result
    },
  },
};
  • The addPerson mutation accepts a name argument
  • When a name is passed, the program will create a new object with a matching name key
  • Next, it will use the push method to add this object to the people dataset
  • Finally, it will return the new object’s properties to the client

That’s it! To test it out, run this code within the Operations window:

#perform a mutation on the server
mutation($name: String) {
  addPerson(name:"Hussain") { #add a new person with the name "Hussain"
    #if the execution succeeds, return its 'id' and 'name` to the user.
    id
    name
  }
}

Addperson

Let’s verify if GraphQL has added the new entry to the database:

query {
  getAllPeople { #get all the results within the 'people' database. 
  #return only their names
  name 
  }
}

Verify That GraphQL Added A New Entry

Building our client

We have successfully built our server. In this section, we will build a client app using Next that will listen to the server and render data to the UI.

As a first step, initialize a blank Next.js app like so:

npx create-next-app@latest graphql-client --ts
touch constants.tsx #our query variables go here.

To perform GraphQL operations, we will use the graphql-request library. This is a minimal, open source module that will help us make mutations and queries on our server:

npm install graphql-request graphql
npm install react-hook-form #to capture user input

Creating query variables

In this section, we will code our queries and mutations to help us make GraphQL operations. To do so, go to constants.tsx and add the following code:

import { gql } from "graphql-request";
//create our query
const getAllPeopleQuery = gql`
  query {
    getAllPeople { #run the getAllPeople command
      id
      name
    }
  }
`;
//Next, declare a mutation
const addPersonMutation = gql`
  mutation addPeople($name: String!) {
    addPerson(name: $name) { #add a new entry. Argument will be 'name'
      id
      name
    }
  }
`;
export { getAllPeopleQuery, addPersonMutation };
  • In the first part, we created the getAllPeopleQuery variable. When the user runs this query, the program will instruct the server to get all the entries present in the database
  • Later on, the addPerson mutation tells GraphQL to add a new entry with its respected name field
  • In the end, we used the export keyword to link our variables with the rest of the project

Performing queries

In pages/index.ts, write the following code:

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request"; //allows us to perform a request on our server
import { getAllPeopleQuery } from "../constants"; 
import Link from "next/link";
const Home: NextPage = ({
  result, //extract the 'result' prop 
}: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <div className={styles.container}>
      {result.map((item: any) => { //render the 'result' array to the UI 
        return <p key={item.id}>{item.name}</p>;
      })}
    <Link href="/addpage">Add a new entry </Link>
    </div>
  );
};
//fetch data from the server
export const getStaticProps: GetStaticProps = async () => {
  //the first argument is the URL of our GraphQL server
  const res = await request("http://localhost:4000/graphql", getAllPeopleQuery);
  const result = res.getAllPeople;
  return {
    props: {
      result,
    }, // will be passed to the page component as props
  };
};
export default Home;

Here is a breakdown of this code piece by piece:

  • In the getStaticProps method, we instructed Next to run the getAllPeople command on our GraphQL server
  • Later on, we returned its response to the Home functional component. This means that we can now render the result to the UI
  • Next, the program used the map method to render all of the results of the getAllPeople command to the UI. Each paragraph element will display the name fields of each entry
  • Furthermore, we also used a Link component to redirect the user to the addpage route. This will allow the user to add a new Person instance to the table

To test out the code, run the following terminal command:

npm run dev

This will be the result:

Addpage Route

Our GraphQL server even updates in real time.

GraphQL Updating In Real Time

Performing mutations

Now that we have successfully performed a query, we can even perform mutations via the graphql-request library.

Within your pages folder, create a new file called addpage.tsx. As the name suggests, this component will allow the user to add a new entry to the database. Here, start by writing the following block of code:

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request";
import { addPersonMutation } from "../constants";
const AddPage: NextPage = () => {
  return (
    <div>
      <p>We will add a new entry here. </p>
    </div>
  );
};
export default AddPage;

In this piece of code, we are creating a blank page with a piece of text. We are doing this to ensure whether our URL routing system works.

Creating A Blank Page To Ensure URL Routing Works

This means that we used routing successfully! Next, write this snippet in your addpage.tsx file:

import { useForm } from "react-hook-form";
const { register, handleSubmit } = useForm();
//if the user submits the form, then the program will output the value of their input.
const onSubmit = (data: any) => console.log(data);
return (
  <div>
    <form onSubmit={handleSubmit(onSubmit)}> {/*Bind our handler to this form.*/}
      {/* The user's input will be saved within the 'name' property */}
      <input defaultValue="test" {...register("name")} />
      <input type="submit" />
    </form>
  </div>
);

This will be the output:

 Output

Now that we have successfully captured the user’s input, our last step is to add their entry to the server.

To do so, change the onSubmit handler located in pages/addpage.tsx file like so:

const onSubmit = async (data: any) => {
  const response = await request(
    "http://localhost:4000/graphql",
    addPersonMutation,
    data
  );
  console.log(response);
};
  • Here, we’re performing a mutation request to our GraphQL server via the request function
  • Furthermore, we also passed in the addPerson mutation command to our request header. This will tell GraphQL to perform the addMutation action on our server

This will be the result:

Result Of Addmutation Action

And we’re done!

Conclusion

Here is the full source code of this project.

In this article, you learned how to create a full-stack app using GraphQL and TypeScript. They both are extremely crucial skills within the programming world since they are in high demand nowadays.

If you encountered any difficulty in this code, I advise you to deconstruct the code and play with it so that you can fully grasp this concept.

Thank you so much for reading! Happy coding!

This story was originally published at https://blog.logrocket.com/build-graphql-app-node-js-typescript-graphql-request/

#graphql #typescript #nodejs 

Saul  Alaniz

Saul Alaniz

1654310400

Cree Una Aplicación GraphQL En Node.js Con TypeScript Y Graphql-reques

En este artículo, creará una aplicación de pila completa utilizando GraphQL y Node.js en el backend. Mientras tanto, nuestro frontend usará la graphql-requestbiblioteca para realizar operaciones de red en nuestro backend.

¿Por qué usar graphql-request y TypeScript?

Cada vez que los desarrolladores construyen un servidor GraphQL usando Apollo, la biblioteca genera una "interfaz" que se ve así:

Esta interfaz permite a los usuarios realizar consultas o solicitudes de mutación al servidor a través de un código. Sin embargo, hablemos del elefante en la habitación: no parece muy fácil de usar. Dado que la interfaz no presenta ningún botón ni ningún elemento de interfaz útil, puede ser difícil para muchos usuarios navegar por su aplicación. En consecuencia, esto reduce su base de usuarios. Entonces, ¿cómo resolvemos este problema?

Aquí es donde graphql-requestentra en juego. Es una biblioteca de código abierto que permite a los usuarios realizar consultas en un servidor GraphQL. Cuenta con las siguientes características:

  • Ligero: esta biblioteca tiene un poco más de 21 kilobytes minimizados, lo que garantiza que su aplicación se mantenga en funcionamiento
  • API basada en promesas: esto brinda soporte para aplicaciones asíncronas
  • Compatibilidad con TypeScript: graphql-requestes una de las muchas bibliotecas que permite TypeScript. Una de las principales ventajas de Typescript es que permite un código estable y predecible.

Por ejemplo, mira el siguiente programa:

let myNumber = 9; //here, myNumber is an integer
myNumber = 'hello'; //now it is a string.
myNumber = myNumber + 10; //even though we are adding a string to an integer,
//JavaScript won't return an error. In the real world, it might bring unexpected outputs.
//However, in Typescript, we can tell the compiler..
//what data types we need to choose.
let myNumber:number = 39; //tell TS that we want to declare an integer.
myNumber = 9+'hello'; //returns an error. Therefore, it's easier to debug the program
//this promises stability and security. 

En este artículo, crearemos una aplicación de pila completa utilizando GraphQL y TypeScript. Aquí, usaremos el apollo-server-expresspaquete para construir un servidor backend. Además, para la interfaz, usaremos Next y graphql-requestconsumiremos nuestra API GraphQL.

Construyendo nuestro servidor

Inicialización del proyecto

Para inicializar un proyecto Node.js en blanco, ejecute estos comandos de terminal:

mkdir graphql-ts-tutorial #create project folder 
cd graphql-ts-tutorial 
npm init -y #initialize the app

Cuando termine, ahora tenemos que decirle a Node que necesitamos usar TypeScript en nuestra base de código:

#configure our Typescript:
npx tsc --init --rootDir app --outDir dist --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
mkdir app #our main code folder
mkdir dist #Typescript will use this folder to compile our program.

A continuación, instale estas dependencias:

#development dependencies. Will tell Node that we will use Typescript
npm install -d ts-node @types/node typescript @types/express nodemon
#Installing Apollo Server and its associated modules. Will help us build our GraphQL
#server
npm install apollo-server-express apollo-server-core express graphql

Después de este paso, navegue a su appcarpeta. Aquí, crea los siguientes archivos:

  • index.ts: Nuestro archivo principal. Esto ejecutará y ejecutará nuestro servidor Express GraphQL
  • dataset.ts: Esto servirá como nuestra base de datos, que se servirá al cliente
  • Resolvers.ts: Este módulo manejará los comandos del usuario. Aprenderemos sobre los resolutores más adelante en este artículo.
  • Schema.ts: como sugiere el nombre, este archivo almacenará los esquemas necesarios para enviar datos al cliente

Al final, la estructura de carpetas debería verse así:

Creando nuestra base de datos

En esta sección, crearemos una base de datos ficticia que se utilizará para enviar los datos solicitados. Para hacerlo, vaya a app/dataset.tsy escriba el siguiente código:

let people: { id: number; name: string }[] = [
  { id: 1, name: "Cassie" },
  { id: 2, name: "Rue" },
  { id: 3, name: "Lexi" },
];
export default people;
  • Primero, creamos una matriz de objetos llamadapeople
  • Esta matriz tendrá dos campos: idde tipo numbery namede tipostring

Definiendo nuestro esquema

Aquí, ahora crearemos un esquema para nuestro servidor GraphQL.

En pocas palabras, un esquema de GraphQL es una descripción del conjunto de datos que los clientes pueden solicitar desde una API. Este concepto es similar al de la biblioteca Mongoose .
Para crear un esquema, vaya al app/Schema.tsarchivo. Allí escribe el siguiente código:

import { gql } from "apollo-server-express"; //will create a schema
const Schema = gql`
  type Person {
    id: ID!
    name: String
  }
  #handle user commands
  type Query {
    getAllPeople: [Person] #will return multiple Person instances
    getPerson(id: Int): Person #has an argument of 'id` of type Integer.
  }
`;
export default Schema; 
//export this Schema so we can use it in our project

Desglosemos este código pieza por pieza:

  • La Schemavariable contiene nuestro esquema GraphQL
  • Primero, creamos un Personesquema. Tendrá dos campos: idde tipo IDy namede tipoString
  • Más adelante, le indicamos a GraphQL que si el cliente ejecuta el getAllPeoplecomando, el servidor devolverá una matriz de Personobjetos
  • Además, si el usuario usa el getPersoncomando, GraphQL devolverá una sola Personinstancia

Creando resolutores

Ahora que hemos codificado nuestro esquema, nuestro siguiente paso es definir nuestros resolutores.
En términos simples, un resolver es un grupo de funciones que generan una respuesta para una consulta de GraphQL. En otras palabras, un resolver sirve como un controlador de consultas GraphQL.
En Resolvers.ts, escribe el siguiente código:

import people from "./dataset"; //get all of the available data from our database.
const Resolvers = {
  Query: {
    getAllPeople: () => people, //if the user runs the getAllPeople command
    //if the user runs the getPerson command:
    getPerson: (_: any, args: any) => { 
      console.log(args);
      //get the object that contains the specified ID.
      return people.find((person) => person.id === args.id);
    },
  },
};
export default Resolvers;
  • Aquí, creamos un Queryobjeto que maneja todas las consultas entrantes que van al servidor
  • Si el usuario ejecuta el getAllPeoplecomando, el programa devolverá todos los objetos presentes en nuestra base de datos
  • Además, el getPersoncomando requiere un argumento id. Esto devolverá una Personinstancia con el ID coincidente
  • Al final, exportamos nuestro resolver para que pudiera vincularse con nuestra aplicación.

Configurando nuestro servidor

¡Ya casi hemos terminado! Ahora que hemos creado tanto nuestro esquema como nuestro resolutor, nuestro siguiente paso es vincularlos.

En index.js, escribe este bloque de código:

import { ApolloServer } from "apollo-server-express";
import Schema from "./Schema";
import Resolvers from "./Resolvers";
import express from "express";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import http from "http";

async function startApolloServer(schema: any, resolvers: any) {
  const app = express();
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    typeDefs: schema,
    resolvers,
    //tell Express to attach GraphQL functionality to the server
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  }) as any;
  await server.start(); //start the GraphQL server.
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve) //run the server on port 4000
  );
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
}
//in the end, run the server and pass in our Schema and Resolver.
startApolloServer(Schema, Resolvers);

¡Vamos a probarlo! Para ejecutar el código, use este comando Bash:

npx nodemon app/index.ts 

Esto creará un servidor en la localhost:4000/graphqlURL.

Aquí puede ver sus esquemas disponibles dentro de la interfaz de usuario:

¡Esto significa que nuestro código funciona!

Todas nuestras consultas de GraphQL irán dentro del panel de Operación . Para verlo en acción, escriba este fragmento dentro de este cuadro:

#make a query:
query {
  #get all of the people available in the server
  getAllPeople {
    #procure their IDs and names.
    id
    name
  }
}

Para ver el resultado, haga clic en el botón Ejecutar :

Incluso podemos buscar una entidad específica a través de la getPersonconsulta:

query ($getPersonId: Int) { #the argument will be of type Integer
  getPerson(id: 1) {
    #get the person with the ID of 1
    name
    id
  }
}

Creando mutaciones

En el mundo de GraphQL, las mutaciones son comandos que tienen efectos secundarios en la base de datos. Ejemplos comunes de esto incluyen:

  • Agregar un usuario a la base de datos: cuando un cliente se registra en un sitio web, el usuario realiza una mutación para guardar sus datos en su base de datos
  • Editar o eliminar un objeto: si un usuario modifica o elimina datos de una base de datos, esencialmente está creando una mutación en el servidor.

Para manejar mutaciones, vaya a su Schema.tsmódulo. Aquí, dentro de la Schemavariable, agregue las siguientes líneas de código:

const Schema = gql`
  #other code..
  type Mutation {
    #the addPerson commmand will accept an argument of type String.
    #it will return a 'Person' instance. 
    addPerson(name: String): Person
  }
`;

Nuestro próximo paso es crear un resolver para manejar esta mutación. Para hacerlo, dentro del Resolvers.tsarchivo, agregue este bloque de código:

const Resolvers = {
  Query: {
    //..further code..
  },
  //code to add:
  //all our mutations go here.
  Mutation: {
    //create our mutation:
    addPerson: (_: any, args: any) => {
      const newPerson = {
        id: people.length + 1, //id field
        name: args.name, //name field
      };
      people.push(newPerson);
      return newPerson; //return the new object's result
    },
  },
};
  • La addPersonmutación acepta un nameargumento.
  • Cuando namese pasa a, el programa creará un nuevo objeto con una nameclave coincidente
  • A continuación, utilizará el pushmétodo para agregar este objeto al conjunto de peopledatos .
  • Finalmente, devolverá las propiedades del nuevo objeto al cliente.

¡Eso es todo! Para probarlo, ejecute este código dentro de la ventana Operaciones :

#perform a mutation on the server
mutation($name: String) {
  addPerson(name:"Hussain") { #add a new person with the name "Hussain"
    #if the execution succeeds, return its 'id' and 'name` to the user.
    id
    name
  }
}

Verifiquemos si GraphQL ha agregado la nueva entrada a la base de datos:

query {
  getAllPeople { #get all the results within the 'people' database. 
  #return only their names
  name 
  }
}

Construyendo nuestro cliente

Hemos construido con éxito nuestro servidor. En esta sección, crearemos una aplicación cliente usando Next que escuchará al servidor y procesará datos en la interfaz de usuario.

Como primer paso, inicialice una aplicación Next.js en blanco así:

npx create-next-app@latest graphql-client --ts
touch constants.tsx #our query variables go here.

Para realizar operaciones GraphQL, utilizaremos la biblioteca graphql-request . Este es un módulo mínimo y de código abierto que nos ayudará a realizar mutaciones y consultas en nuestro servidor:

npm install graphql-request graphql
npm install react-hook-form #to capture user input

Creación de variables de consulta

En esta sección, codificaremos nuestras consultas y mutaciones para ayudarnos a realizar operaciones GraphQL. Para hacerlo, vaya a constants.tsxy agregue el siguiente código:

import { gql } from "graphql-request";
//create our query
const getAllPeopleQuery = gql`
  query {
    getAllPeople { #run the getAllPeople command
      id
      name
    }
  }
`;
//Next, declare a mutation
const addPersonMutation = gql`
  mutation addPeople($name: String!) {
    addPerson(name: $name) { #add a new entry. Argument will be 'name'
      id
      name
    }
  }
`;
export { getAllPeopleQuery, addPersonMutation };
  • En la primera parte, creamos la getAllPeopleQueryvariable. Cuando el usuario ejecuta esta consulta, el programa le indicará al servidor que obtenga todas las entradas presentes en la base de datos.
  • Más tarde, la addPersonmutación le dice a GraphQL que agregue una nueva entrada con su namecampo respectivo
  • Al final, usamos la exportpalabra clave para vincular nuestras variables con el resto del proyecto.

Realización de consultas

En pages/index.ts, escribe el siguiente código:

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request"; //allows us to perform a request on our server
import { getAllPeopleQuery } from "../constants"; 
import Link from "next/link";
const Home: NextPage = ({
  result, //extract the 'result' prop 
}: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <div className={styles.container}>
      {result.map((item: any) => { //render the 'result' array to the UI 
        return <p key={item.id}>{item.name}</p>;
      })}
    <Link href="/addpage">Add a new entry </Link>
    </div>
  );
};
//fetch data from the server
export const getStaticProps: GetStaticProps = async () => {
  //the first argument is the URL of our GraphQL server
  const res = await request("http://localhost:4000/graphql", getAllPeopleQuery);
  const result = res.getAllPeople;
  return {
    props: {
      result,
    }, // will be passed to the page component as props
  };
};
export default Home;

Aquí hay un desglose de este código pieza por pieza:

  • En el getStaticPropsmétodo, le indicamos a Next que ejecute el getAllPeoplecomando en nuestro servidor GraphQL
  • Posteriormente, devolvimos su respuesta al Homecomponente funcional. Esto significa que ahora podemos mostrar el resultado en la interfaz de usuario.
  • A continuación, el programa usó el mapmétodo para representar todos los resultados del getAllPeoplecomando en la interfaz de usuario. Cada elemento de párrafo mostrará los namecampos de cada entrada
  • Además, también usamos un Linkcomponente para redirigir al usuario a la addpageruta. Esto permitirá al usuario agregar una nueva Personinstancia a la tabla .

Para probar el código, ejecute el siguiente comando de terminal:

npm run dev

Este será el resultado:

Nuestro servidor GraphQL incluso se actualiza en tiempo real.

Realizando mutaciones

Ahora que hemos realizado con éxito una consulta, incluso podemos realizar mutaciones a través de la graphql-requestbiblioteca.

Dentro de su pagescarpeta, cree un nuevo archivo llamado addpage.tsx. Como sugiere el nombre, este componente permitirá al usuario agregar una nueva entrada a la base de datos. Aquí, comience escribiendo el siguiente bloque de código:

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request";
import { addPersonMutation } from "../constants";
const AddPage: NextPage = () => {
  return (
    <div>
      <p>We will add a new entry here. </p>
    </div>
  );
};
export default AddPage;

En este fragmento de código, estamos creando una página en blanco con un fragmento de texto. Estamos haciendo esto para asegurarnos de que nuestro sistema de enrutamiento de URL funcione.

¡Esto significa que usamos el enrutamiento con éxito! A continuación, escribe este fragmento en tu addpage.tsxarchivo:

import { useForm } from "react-hook-form";
const { register, handleSubmit } = useForm();
//if the user submits the form, then the program will output the value of their input.
const onSubmit = (data: any) => console.log(data);
return (
  <div>
    <form onSubmit={handleSubmit(onSubmit)}> {/*Bind our handler to this form.*/}
      {/* The user's input will be saved within the 'name' property */}
      <input defaultValue="test" {...register("name")} />
      <input type="submit" />
    </form>
  </div>
);

Esta será la salida:

 

Ahora que hemos capturado con éxito la entrada del usuario, nuestro último paso es agregar su entrada al servidor.

Para hacerlo, cambie el onSubmitcontrolador ubicado en pages/addpage.tsxel archivo de esta manera:

const onSubmit = async (data: any) => {
  const response = await request(
    "http://localhost:4000/graphql",
    addPersonMutation,
    data
  );
  console.log(response);
};
  • Aquí, estamos realizando una solicitud de mutación a nuestro servidor GraphQL a través de la requestfunción
  • Además, también pasamos el addPersoncomando de mutación a nuestro encabezado de solicitud. Esto le indicará a GraphQL que realice la addMutationacción en nuestro servidor

Este será el resultado:

¡Y hemos terminado!

Conclusión

Aquí está el código fuente completo de este proyecto.

En este artículo, aprendió a crear una aplicación completa con GraphQL y TypeScript. Ambas son habilidades extremadamente cruciales dentro del mundo de la programación, ya que tienen una gran demanda en la actualidad.

Si encontró alguna dificultad en este código, le aconsejo que deconstruya el código y juegue con él para que pueda comprender completamente este concepto.

Muchas Gracias Por Leer! ¡Feliz codificación!

Esta historia se publicó originalmente en https://blog.logrocket.com/build-graphql-app-node-js-typescript-graphql-request/

#graphql #typescript #nodejs 

坂本  篤司

坂本 篤司

1654310040

TypeScriptとgraphql-requestを使用してNode.jsでGraphQLアプリを構築します

この記事では、バックエンドでGraphQLとNode.jsを使用してフルスタックアプリを構築します。一方、フロントエンドはgraphql-requestライブラリを使用してバックエンドでネットワーク操作を実行します。

なぜgraphql-requestとTypeScriptを使用するのですか?

開発者がApolloを使用してGraphQLサーバーを構築するときはいつでも、ライブラリは次のような「フロントエンド」を生成します。

このインターフェースにより、ユーザーはコードを介してサーバーにクエリまたはミューテーション要求を行うことができます。ただし、部屋の中の象について説明しましょう。あまりユーザーフレンドリーではないようです。フロントエンドにはボタンや便利なインターフェース要素がないため、多くのユーザーがアプリ内を移動するのは難しいかもしれません。その結果、これによりユーザーベースが縮小します。では、この問題をどのように解決するのでしょうか。

これがgraphql-request出番です。これは、ユーザーがGraphQLサーバーでクエリを実行できるようにするオープンソースライブラリです。次の機能を備えています。

  • 軽量—このライブラリは21キロバイトをわずかに超える最小化されているため、アプリのパフォーマンスを維持できます
  • PromiseベースのAPI—これにより非同期アプリケーションのサポートがもたらされます
  • TypeScriptのサポート—TypeScriptgraphql-requestを可能にする多くのライブラリの1つです。Typescriptの主な利点の1つは、安定した予測可能なコードが可能になることです。

たとえば、次のプログラムを見てください。

let myNumber = 9; //here, myNumber is an integer
myNumber = 'hello'; //now it is a string.
myNumber = myNumber + 10; //even though we are adding a string to an integer,
//JavaScript won't return an error. In the real world, it might bring unexpected outputs.
//However, in Typescript, we can tell the compiler..
//what data types we need to choose.
let myNumber:number = 39; //tell TS that we want to declare an integer.
myNumber = 9+'hello'; //returns an error. Therefore, it's easier to debug the program
//this promises stability and security. 

この記事では、GraphQLとTypeScriptを使用してフルスタックアプリを構築します。ここでは、apollo-server-expressパッケージを使用してバックエンドサーバーを構築します。さらに、フロントエンドでは、Nextを使用graphql-requestしてGraphQLAPIを使用します。

サーバーの構築

プロジェクトの初期化

空のNode.jsプロジェクトを初期化するには、次のターミナルコマンドを実行します。

mkdir graphql-ts-tutorial #create project folder 
cd graphql-ts-tutorial 
npm init -y #initialize the app

それが終わったら、コードベースでTypeScriptを使用する必要があることをNodeに通知する必要があります。

#configure our Typescript:
npx tsc --init --rootDir app --outDir dist --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
mkdir app #our main code folder
mkdir dist #Typescript will use this folder to compile our program.

次に、次の依存関係をインストールします。

#development dependencies. Will tell Node that we will use Typescript
npm install -d ts-node @types/node typescript @types/express nodemon
#Installing Apollo Server and its associated modules. Will help us build our GraphQL
#server
npm install apollo-server-express apollo-server-core express graphql

この手順の後、appフォルダに移動します。ここで、次のファイルを作成します。

  • index.ts:メインファイル。これにより、ExpressGraphQLサーバーが実行されます。
  • dataset.ts:これは、クライアントに提供されるデータベースとして機能します
  • Resolvers.ts:このモジュールはユーザーコマンドを処理します。リゾルバーについては、この記事の後半で学習します
  • Schema.ts:名前が示すように、このファイルには、クライアントにデータを送信するために必要な回路図が保存されます

最終的に、フォルダ構造は次のようになります。

データベースの作成

このセクションでは、要求されたデータを送信するために使用されるダミーデータベースを作成します。これを行うには、に移動しapp/dataset.tsて次のコードを記述します。

let people: { id: number; name: string }[] = [
  { id: 1, name: "Cassie" },
  { id: 2, name: "Rue" },
  { id: 3, name: "Lexi" },
];
export default people;
  • まず、というオブジェクトの配列を作成しましたpeople
  • この配列には、タイプとidタイプの2つのフィールドがあります。numbernamestring

スキーマの定義

ここでは、GraphQLサーバーのスキーマを作成します。

簡単に言うと、GraphQLスキーマは、クライアントがAPIから要求できるデータセットの記述です。この概念は、マングースライブラリの概念に似ています。
スキーマを作成するには、app/Schema.tsファイルに移動します。そこで、次のコードを記述します。

import { gql } from "apollo-server-express"; //will create a schema
const Schema = gql`
  type Person {
    id: ID!
    name: String
  }
  #handle user commands
  type Query {
    getAllPeople: [Person] #will return multiple Person instances
    getPerson(id: Int): Person #has an argument of 'id` of type Integer.
  }
`;
export default Schema; 
//export this Schema so we can use it in our project

このコードを1つずつ分解してみましょう。

  • 変数にはSchemaGraphQLスキーマが含まれています
  • まず、Personスキーマを作成しました。idタイプIDnameタイプの2つのフィールドがありますString
  • 後で、クライアントがコマンドを実行すると、サーバーがオブジェクトgetAllPeopleの配列を返すようにGraphQLに指示しました。Person
  • さらに、ユーザーがgetPersonコマンドを使用すると、GraphQLは単一のPersonインスタンスを返します

リゾルバーの作成

スキーマをコーディングしたので、次のステップはリゾルバーを定義することです。
簡単に言うと、リゾルバーはGraphQLクエリの応答を生成する関数のグループです。つまり、リゾルバーはGraphQLクエリハンドラーとして機能します。
Resolvers.ts、次のコードを記述します。

import people from "./dataset"; //get all of the available data from our database.
const Resolvers = {
  Query: {
    getAllPeople: () => people, //if the user runs the getAllPeople command
    //if the user runs the getPerson command:
    getPerson: (_: any, args: any) => { 
      console.log(args);
      //get the object that contains the specified ID.
      return people.find((person) => person.id === args.id);
    },
  },
};
export default Resolvers;
  • ここではQuery、サーバーに送信されるすべての着信クエリを処理するオブジェクトを作成しました
  • ユーザーがgetAllPeopleコマンドを実行すると、プログラムはデータベースに存在するすべてのオブジェクトを返します
  • さらに、getPersonコマンドには引数が必要idです。Personこれにより、IDが一致するインスタンスが返されます
  • 最終的に、アプリとリンクできるようにリゾルバーをエクスポートしました

サーバーの構成

ほぼ完了です。スキーマとリゾルバーの両方を構築したので、次のステップはそれらをリンクすることです。

index.js、次のコードブロックを記述します。

import { ApolloServer } from "apollo-server-express";
import Schema from "./Schema";
import Resolvers from "./Resolvers";
import express from "express";
import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
import http from "http";

async function startApolloServer(schema: any, resolvers: any) {
  const app = express();
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    typeDefs: schema,
    resolvers,
    //tell Express to attach GraphQL functionality to the server
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  }) as any;
  await server.start(); //start the GraphQL server.
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve) //run the server on port 4000
  );
  console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
}
//in the end, run the server and pass in our Schema and Resolver.
startApolloServer(Schema, Resolvers);

テストしてみましょう!コードを実行するには、次のBashコマンドを使用します。

npx nodemon app/index.ts 

これにより、URLにサーバーが作成されlocalhost:4000/graphqlます。

ここで、UI内で使用可能なスキーマを確認できます。

これは、コードが機能することを意味します。

すべてのGraphQLクエリは操作パネル内にあります。実際の動作を確認するには、次のボックスに次のスニペットを入力してください。

#make a query:
query {
  #get all of the people available in the server
  getAllPeople {
    #procure their IDs and names.
    id
    name
  }
}

結果を確認するには、[実行]ボタンをクリックします。

getPersonクエリを介して特定のエンティティを検索することもできます。

query ($getPersonId: Int) { #the argument will be of type Integer
  getPerson(id: 1) {
    #get the person with the ID of 1
    name
    id
  }
}

突然変異の作成

GraphQLの世界では、ミューテーションはデータベースに副作用をもたらすコマンドです。この一般的な例は次のとおりです。

  • データベースへのユーザーの追加—クライアントがWebサイトにサインアップすると、ユーザーはミューテーションを実行してデータをデータベースに保存します
  • オブジェクトの編集または削除—ユーザーがデータベースからデータを変更または削除した場合、基本的にサーバー上にミューテーションが作成されます。

ミューテーションを処理するには、Schema.tsモジュールに移動します。ここで、Schema変数内に次のコード行を追加します。

const Schema = gql`
  #other code..
  type Mutation {
    #the addPerson commmand will accept an argument of type String.
    #it will return a 'Person' instance. 
    addPerson(name: String): Person
  }
`;

次のステップは、このミューテーションを処理するためのリゾルバーを作成することです。これを行うには、Resolvers.tsファイル内に次のコードブロックを追加します。

const Resolvers = {
  Query: {
    //..further code..
  },
  //code to add:
  //all our mutations go here.
  Mutation: {
    //create our mutation:
    addPerson: (_: any, args: any) => {
      const newPerson = {
        id: people.length + 1, //id field
        name: args.name, //name field
      };
      people.push(newPerson);
      return newPerson; //return the new object's result
    },
  },
};
  • 突然変異は引数addPersonを受け入れますname
  • aが渡されると、プログラムは一致するキーnameを持つ新しいオブジェクトを作成しますname
  • 次に、メソッドを使用してこのオブジェクトをデータセットpushに追加しますpeople
  • 最後に、新しいオブジェクトのプロパティをクライアントに返します

それでおしまい!テストするには、[操作]ウィンドウ内で次のコードを実行します。

#perform a mutation on the server
mutation($name: String) {
  addPerson(name:"Hussain") { #add a new person with the name "Hussain"
    #if the execution succeeds, return its 'id' and 'name` to the user.
    id
    name
  }
}

GraphQLがデータベースに新しいエントリを追加したかどうかを確認しましょう。

query {
  getAllPeople { #get all the results within the 'people' database. 
  #return only their names
  name 
  }
}

クライアントの構築

サーバーの構築に成功しました。このセクションでは、Nextを使用して、サーバーをリッスンし、UIにデータをレンダリングするクライアントアプリを構築します。

最初のステップとして、次のように空のNext.jsアプリを初期化します。

npx create-next-app@latest graphql-client --ts
touch constants.tsx #our query variables go here.

GraphQL操作を実行するには、graphql-requestライブラリーを使用します。これは最小限のオープンソースモジュールであり、サーバーでミューテーションとクエリを実行するのに役立ちます。

npm install graphql-request graphql
npm install react-hook-form #to capture user input

クエリ変数の作成

このセクションでは、GraphQL操作を行うのに役立つクエリとミューテーションをコーディングします。これを行うには、に移動しconstants.tsxて次のコードを追加します。

import { gql } from "graphql-request";
//create our query
const getAllPeopleQuery = gql`
  query {
    getAllPeople { #run the getAllPeople command
      id
      name
    }
  }
`;
//Next, declare a mutation
const addPersonMutation = gql`
  mutation addPeople($name: String!) {
    addPerson(name: $name) { #add a new entry. Argument will be 'name'
      id
      name
    }
  }
`;
export { getAllPeopleQuery, addPersonMutation };
  • 最初の部分では、getAllPeopleQuery変数を作成しました。ユーザーがこのクエリを実行すると、プログラムはサーバーにデータベースに存在するすべてのエントリを取得するように指示します
  • 後で、addPersonミューテーションはGraphQLに、尊重されたnameフィールドを持つ新しいエントリを追加するように指示します
  • 最後に、exportキーワードを使用して変数をプロジェクトの残りの部分にリンクしました

クエリの実行

pages/index.ts、次のコードを記述します。

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request"; //allows us to perform a request on our server
import { getAllPeopleQuery } from "../constants"; 
import Link from "next/link";
const Home: NextPage = ({
  result, //extract the 'result' prop 
}: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <div className={styles.container}>
      {result.map((item: any) => { //render the 'result' array to the UI 
        return <p key={item.id}>{item.name}</p>;
      })}
    <Link href="/addpage">Add a new entry </Link>
    </div>
  );
};
//fetch data from the server
export const getStaticProps: GetStaticProps = async () => {
  //the first argument is the URL of our GraphQL server
  const res = await request("http://localhost:4000/graphql", getAllPeopleQuery);
  const result = res.getAllPeople;
  return {
    props: {
      result,
    }, // will be passed to the page component as props
  };
};
export default Home;

このコードの内訳は次のとおりです。

  • このメソッドでは、GraphQLサーバーでコマンドgetStaticPropsを実行するようにNextに指示しましたgetAllPeople
  • Homeその後、機能コンポーネントへの応答を返しました。これは、結果をUIにレンダリングできることを意味します
  • 次に、プログラムはこのメソッドを使用して、コマンドのすべての結果をUImapにレンダリングしました。getAllPeople各段落要素にはname、各エントリのフィールドが表示されます
  • さらに、コンポーネントを使用してユーザーをルートLinkにリダイレクトしました。addpageこれにより、ユーザーPersonはテーブルに新しいインスタンスを追加できます

コードをテストするには、次のターミナルコマンドを実行します。

npm run dev

これが結果になります:

GraphQLサーバーはリアルタイムで更新されます。

突然変異の実行

graphql-requestクエリの実行に成功したので、ライブラリを介してミューテーションを実行することもできます。

フォルダ内pagesに、という名前の新しいファイルを作成しますaddpage.tsx。名前が示すように、このコンポーネントを使用すると、ユーザーはデータベースに新しいエントリを追加できます。ここでは、次のコードブロックを作成することから始めます。

import type { NextPage, GetStaticProps, InferGetStaticPropsType } from "next";
import { request } from "graphql-request";
import { addPersonMutation } from "../constants";
const AddPage: NextPage = () => {
  return (
    <div>
      <p>We will add a new entry here. </p>
    </div>
  );
};
export default AddPage;

このコードでは、テキストを含む空白のページを作成しています。これは、URLルーティングシステムが機能するかどうかを確認するために行っています。

これは、ルーティングを正常に使用したことを意味します。次に、このスニペットをaddpage.tsxファイルに書き込みます。

import { useForm } from "react-hook-form";
const { register, handleSubmit } = useForm();
//if the user submits the form, then the program will output the value of their input.
const onSubmit = (data: any) => console.log(data);
return (
  <div>
    <form onSubmit={handleSubmit(onSubmit)}> {/*Bind our handler to this form.*/}
      {/* The user's input will be saved within the 'name' property */}
      <input defaultValue="test" {...register("name")} />
      <input type="submit" />
    </form>
  </div>
);

これが出力になります:

 

ユーザーの入力を正常にキャプチャしたので、最後のステップはサーバーにユーザーのエントリを追加することです。

これを行うには、ファイルにあるonSubmitハンドラーを次のように変更します。pages/addpage.tsx

const onSubmit = async (data: any) => {
  const response = await request(
    "http://localhost:4000/graphql",
    addPersonMutation,
    data
  );
  console.log(response);
};
  • requestここでは、関数を介してGraphQLサーバーへのミューテーションリクエストを実行しています
  • さらに、addPersonmutationコマンドをリクエストヘッダーにも渡しました。これにより、GraphQLにaddMutationサーバーでアクションを実行するように指示されます

これが結果になります:

これで完了です。

結論

これがこのプロジェクトの完全なソースコードです。

この記事では、GraphQLとTypeScriptを使用してフルスタックアプリを作成する方法を学びました。これらは両方とも、今日需要が高いため、プログラミングの世界では非常に重要なスキルです。

このコードで問題が発生した場合は、この概念を完全に理解できるように、コードを分解して試してみることをお勧めします。

読んでくれてありがとう!ハッピーコーディング!

このストーリーは、もともとhttps://blog.logrocket.com/build-graphql-app-node-js-typescript-graphql-request/で公開されました

#graphql #typescript #nodejs