国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is GraphQL?
What are we building
start
GraphQL schema type
GraphQL parser
Query
Mutations
Summarize
Home Web Front-end CSS Tutorial Get Started Building GraphQL APIs With Node

Get Started Building GraphQL APIs With Node

Apr 09, 2025 am 09:14 AM

Get Started Building GraphQL APIs With Node

We all have many interests and hobbies. For example, I'm interested in JavaScript, '90s indie rock and hip-hop, unpopular jazz, the city of Pittsburgh, pizza, coffee, and movies starring John Lury. Our family, friends, acquaintances, classmates and colleagues also have their own social relationships, interests and hobbies. Some of these relationships and interests overlap, like my friend Riley is just as interested in 90s hip-hop and pizza as I do. Others have no overlap, such as my colleague Harrison, who prefers Python over JavaScript, drinks only tea and prefers current pop music. All in all, each of us has a map of connection with people in our lives and how our relationships and interests overlap.

This type of interrelated data is exactly the challenge GraphQL initially started to solve in API development. By writing the GraphQL API, we are able to effectively connect data, reducing complexity and request count while allowing us to provide the required data to the client accurately. (If you prefer the GraphQL metaphor, check out Meet GraphQL at a cocktail party.)

In this article, we will use the Apollo Server package to build a GraphQL API in Node.js. To do this, we will explore the basic GraphQL topic, write GraphQL patterns, develop code to parse our pattern functions, and access our API using the GraphQL Playground user interface.

What is GraphQL?

GraphQL is an open source query and data manipulation language for APIs. Its development goal is to provide a single endpoint for data, allowing applications to request the exact data they need. This not only helps simplify our UI code, but also improves performance by limiting the amount of data that needs to be sent over the network.

What are we building

To follow this tutorial, you need Node v8.x or later and some experience using the command line.

We will build an API application for book excerpts that allow us to store memorable paragraphs from what we read. API users will be able to perform "CRUD" (create, read, update, delete) operations on their excerpts:

  • Create a new excerpt
  • Read a single excerpt and a list of excerpts
  • Updated excerpts
  • Delete the excerpt

start

First, create a new directory for our project, initialize a new node project, and install the dependencies we need:

 <code># 創(chuàng)建新目錄mkdir highlights-api # 進(jìn)入目錄cd highlights-api # 初始化新的節(jié)點項目npm init -y # 安裝項目依賴項npm install apollo-server graphql # 安裝開發(fā)依賴項npm install nodemon --save-dev</code>

Before we proceed, let's break down our dependencies:

  • apollo-server is a library that allows us to use GraphQL in our Node applications. We will use this as a standalone library, but the Apollo team has also created middleware for working with Express, hapi, Fastify, and Koa in existing Node web applications.
  • graphql contains the GraphQL language and is a required peer dependency for apollo-server .
  • nodemon is a useful library that will monitor our project for changes and automatically restart our server.

After installing our package, let's create the root file of the application, named index.js . Now, we will use console.log() to output a message in this file:

 <code>console.log("? Hello Highlights");</code>

To simplify our development process, we will update scripts object in the package.json file to use nodemon package:

 <code>"scripts": { "start": "nodemon index.js" },</code>

Now we can start our application by typing npm start in the terminal application. If everything works fine, will you see ? Hello Highlights logged to your terminal.

GraphQL schema type

Patterns are written representations of our data and interactions. Through the Required Pattern, GraphQL implements strict planning for our API. This is because the API can only return data defined in the schema and perform interactions. The basic component of the GraphQL pattern is the object type. GraphQL contains five built-in types:

  • String: strings encoded using UTF-8 characters
  • Boolean: True or false value
  • Int: 32-bit integer
  • Float: Float value
  • ID: Unique identifier

We can use these basic components to build patterns for APIs. In a file called schema.js , we can import the gql library and prepare the file for our schema syntax:

 <code>const { gql } = require('apollo-server'); const typeDefs = gql` # 模式將放在這里`; module.exports = typeDefs;</code>

To write our pattern, we first define the type. Let's consider how we define patterns for our excerpt application. First, we will create a new type called Highlight :

 <code>const typeDefs = gql` type Highlight { } `;</code>

Each excerpt will have a unique ID, some content, title, and author. The Highlight mode will look like this:

 <code>const typeDefs = gql` type Highlight {  id: ID  content: String  title: String  author: String } `;</code>

We can make some of these fields a required field by adding an exclamation mark:

 <code>const typeDefs = gql` type Highlight {  id: ID!  content: String!  title: String  author: String } `;</code>

Although we have defined an object type for our excerpt, we also need to describe how the client gets that data. This is called a query. We'll dive into the query later, but now let's describe how someone retrieves excerpts in our pattern. When all of our excerpts are requested, the data will be returned as an array (denoted as [Highlight] ), and when we want to retrieve a single excerpt we need to pass the ID as a parameter.

 <code>const typeDefs = gql` type Highlight {  id: ID!  content: String!  title: String  author: String } type Query {  highlights: [Highlight]!  highlight(id: ID!): Highlight } `;</code>

Now, in the index.js file, we can import our type definition and set up Apollo Server:

 <code>const {ApolloServer } = require('apollo-server'); const typeDefs = require('./schema'); const server = new ApolloServer({ typeDefs }); server.listen().then(({ url }) => { console.log(`? Highlights server ready at ${url}`); });</code>

If we keep the node process running, the application will be updated and restarted automatically, but if not, typing npm start from the project's directory in the terminal window will start the server. If we look at the terminal, we should see that nodemon is monitoring our files and the server is running on the local port:

 <code>[nodemon] 2.0.2 [nodemon] to restart at any time, enter `rs` [nodemon] watching dir(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node index.js` ? Highlights server ready at http://localhost:4000/</code>

Accessing the URL in a browser launches the GraphQL Playground application, which provides a user interface for interacting with our API.

GraphQL parser

Although we have developed our project using initial mode and Apollo Server settings, we are not able to interact with our API yet. To do this, we will introduce the parser. The parsers perform the exact operations implied by their name; they parse data requested by the API user. We will write these parsers by first defining them in our schema and then implementing logic in our JavaScript code. Our API will contain two types of parsers: query and mutation.

Let's first add some data to interact with. In an application, this is usually the data we retrieve and write from the database, but for our example, let's use an array of objects. Add the following to the index.js file:

 let highlights = [
  {
    id: '1',
    content: 'One day I will find the right words, and they will be simple.',
    title: 'Dharma Bums',
    author: 'Jack Kerouac'
  },
  {
    id: '2',
    content: 'In the limits of a situation there is humor, there is grace, and everything else.',
    title: 'Arbitrary Stupid Goal',
    author: 'Tamara Shopsin'
  }
]

Query

Query requests specific data from the API and displays it in its desired format. The query will then return an object containing the data requested by the API user. A query never modifies data; it only accesses data. We have written two queries in the schema. The first returns an array of excerpts, and the second returns a specific excerpt. The next step is to write a parser that will return the data.

In the index.js file, we can add a resolvers object that can contain our query:

 const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  }
};

highlights query returns a complete array of excerpt data. highlight query accepts two parameters: parent and args . parent is the first parameter to any GraqhQL query in Apollo Server and provides a way to access the query context. The args parameter allows us to access user-provided parameters. In this case, the API user will provide id parameter to access a specific excerpt.

We can then update our Apollo Server configuration to include the resolver:

 const server = new ApolloServer({ typeDefs, resolvers });

After writing our query parser and updating Apollo Server, we can now use the GraphQL Playground query API. To access GraphQL Playground, visit http://localhost:4000 in your web browser.

The query format is as follows:

 query {
  queryName {
      field
      field
    }
}

With this in mind, we can write a query that requests the ID, content, title, and author of each of our excerpts:

 query {
  highlights {
    id
    content
    title
    author
  }
}

Suppose we have a page in the UI that lists only the title and author of our highlighted text. We don't need to retrieve the content of each excerpt. Instead, we can write a query that only requests the data we need:

 query {
  highlights {
    title
    author
  }
}

We also wrote a parser that querys individual comments by including ID parameters in our query. We can do this:

 query {
  highlight(id: "1") {
    content
  }
}

Mutations

When we want to modify data in the API, we use mutations. In our excerpt example, we will want to write a variant to create a new excerpt, an updated existing excerpt, and a third to delete excerpt. Similar to a query, mutations should also return results in the form of objects, usually the final result of the operation performed.

The first step in updating anything in GraphQL is writing patterns. We can include variants in the schema by adding a variant type to our schema.js file:

 type Mutation {
  newHighlight (content: String! title: String author: String): Highlight!
  updateHighlight(id: ID! content: String!): Highlight!
  deleteHighlight(id: ID!): Highlight!
}

Our newHighlight variant will take the required value of content and optional title and author values ??and return a Highlight . updateHighlight variant will require highlight id and content to be passed as parameter values ??and will return the updated Highlight . Finally, the deleteHighlight variant will accept an ID parameter and will return the deleted Highlight .

After updating the pattern to include mutations, we can now update resolvers in the index.js file to perform these operations. Each mutation updates our highlights data array.

 const resolvers = {
  Query: {
    highlights: () => highlights,
    highlight: (parent, args) => {
      return highlights.find(highlight => highlight.id === args.id);
    }
  },
  Mutation: {
    newHighlight: (parent, args) => {
      const highlight = {
        id: String(highlights.length 1),
        title: args.title || '',
        author: args.author || '',
        content: args.content
      };
      highlights.push(highlight);
      return highlight;
    },
    updateHighlight: (parent, args) => {
      const index = highlights.findIndex(highlight => highlight.id === args.id);
      const highlight = {
        id: args.id,
        content: args.content,
        author: highlights[index].author,
        title: highlights[index].title
      };
      highlights[index] = highlight;
      return highlight;
    },
    deleteHighlight: (parent, args) => {
      const deletedHighlight = highlights.find(
        highlight => highlight.id === args.id
      );
      highlights = highlights.filter(highlight => highlight.id !== args.id);
      return deletedHighlight;
    }
  }
};

After writing these mutations, we can practice mutation data using GraphQL Playground. The structure of the mutation is almost the same as the query, specifying the name of the mutation, passing parameter values, and requesting the return of specific data. Let's first add a new excerpt:

 mutation {
  newHighlight(author: "Adam Scott" title: "JS Everywhere" content: "GraphQL is awesome") {
    id
    author
    title
    content
  }
}

We can then write a mutation to update the excerpt:

 mutation {
  updateHighlight(id: "3" content: "GraphQL is rad") {
    id
    content
  }
}

And delete excerpts:

 mutation {
  deleteHighlight(id: "3") {
    id
  }
}

Summarize

Congratulations! You have now successfully built a GraphQL API that uses Apollo Server and can run GraphQL queries and mutations on in-memory data objects. We have laid a solid foundation for exploring the world of GraphQL API development.

Here are some next steps to improve your level:

  • Learn about nested GraphQL queries and mutations.
  • Follow the Apollo full stack tutorial.
  • Update the example to include a database such as MongoDB or PostgreSQL.
  • Explore more excellent CSS-Tricks GraphQL articles.
  • Use your newly acquired GraphQL knowledge to build static websites using Gatsby.

The above is the detailed content of Get Started Building GraphQL APIs With Node. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles