In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to realize the real-time market of bitcoin by NodeJS and GraphQL". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how NodeJS and GraphQL realize the real-time Bitcoin quotation.
1. Create a project directory
From the terminal, execute the following command to create a new directory and enter it:
Mkdir btc-gql-api & & cd btc-gql-api2, initialization project
Execute yarn init to initialize the project directory in the terminal, and the resulting package.json is similar to the following:
{"name": "my-new-project", "version": "1.0.0", "description": "My New Project description.", "main": "index.js", "repository": {"url": "https://example.com/your-username/my-new-project"," type ":" git "}," author ":" Your Name "," license ":" MIT "}
Execute touch index.js on the terminal to create an empty js file, and then add the following to the package.json:
... "scripts": {"start": "node index.js"},...
The final package.json file looks like this:
{"name": "my-new-project", "version": "1.0.0", "description": "My New Project description.", "main": "index.js", "scripts": {"start": "node index.js"}, "repository": {"url": "https://example.com/your-username/my-new-project"," type ":" git "} "author": "Your Name", "license": "MIT"}
Create a graph directory in the project directory and get the following directory structure:
+ btc-gql-api | _ _ graphql | _ _ package.json | _ _ index.json
Create three js files in the graph directory: types.js, resolver.js, and request.js, and end up with the following directory structure:
+ btc-gql-api | _ _ + graphql | _ request.js | _ resolvers.js | _ types.js | _ _ package.json | _ _ index.json3, installation dependency package
In this project, we will need axios and graphql-yoga, so execute the following command from the project root:
Yarn add axios graphql-yoga
All right, you can start writing code.
4. Type definition
The most basic component in GraphQL Schema is the object type, which identifies the object type that you can extract from the service and which fields it contains. For example:
Type User {name: String! Email: String!}
GraphQL has some built-in base types:
Int:32 bit signed integer
Float: double precision signed floating point number
String:UTF-8 character sequence
Boolean: Boolean, true or false
ID: unique identifier, usually used as a key for an object
You can refer to graphql schema for more detailed documentation.
Now let's define the type. Open the. / graphql/types.js file and enter the following:
Const typeDefs = `scalar JSONtype Price {price:JSON!} `; module.exports = typeDefs
In the above code, we define a type Price, which has only one non-empty field price, and the field type is JSON:
Type Price {price:JSON!}
JSON is not a built-in type of graphql, but is customized by us:
Scalar JSON5, query
GraphQL is about data management, and queries are basically the specified fields of the request object. For example:
Query {getPrices {price}}
The results are as follows:
{"data": {"getPrices": {"price": {"USD": {"15m": 10436.54, "last": 10436.54, "buy": 10436.54, "sell": 10436.54, "symbol": "$"}.}
As you can see, the query result has the same structure as the request.
6. Query and modify
There are two types within a schema: query and mutation.
Each GraphQL service has at least one query type and possibly one modification type. These types are the same as regular object types, but they define the entry point for each GraphQL query. It looks like this:
Scalar JSONtype Price {price:JSON!} type Query {getPrices: Price! GetPrice (currency:String!): Price!}
What the above code means is that our GraphQL service has a Query type that contains getPrices and getPrice fields, both of type Price. We can also see that the field getPrice has parameters (currency:String!). Each field in the GraphQL object type can have 0 or more parameters.
Parameters can be required or optional, and in the above example, we require a required parameter, currency, to select the currency to query.
7. Request assistive tools
Before we continue with GraphQL, we need an auxiliary tool to get the real-time price of bitcoin. To do this, we will use blockchain.com 's API, but you can switch to any service you like.
Open the. / graphql/request.js file and enter the following:
Const axios = require ("axios"); module.exports = {getPrices: async () = > {const url = "https://blockchain.info/ticker"; try {return await axios.get (url);} catch (error) {console.error (error);}
The above code uses axios to construct GET requests, but you can also replace them with other tools you are familiar with.
8. Parser
There is a parser function behind each field of each type, which should be provided by the GraphQL server developer. When a field is executed, the corresponding parser is called and the result is generated.
If a field generates a scalar value such as a string or number, the execution ends. However, if one field generates an object value, the query will contain other fields, which will continue to parse until the resulting fields are scalar values.
At the top of each GraphQL service are all possible entry types, often referred to as the Root type or the Query type.
Open the file. / graphql/resolvers.js and enter the following:
Const requests = require (". / requests"); const resolvers = {Query: {/ / Get all available prices async getPrices (parent, args, ctx, info) {const prices = await requests.getPrices (); return {price: prices.data};}, / / Get the price of a given currency symbol async getPrice (parent, args, ctx, info) {const prices = await requests.getPrices () Return {price: {[args ["currency"]]: prices.data [args ["currency"]}};}; module.exports = resolvers
Let's break down and explain the above code.
First of all, introduce our auxiliary tool to query the real-time market of Bitcoin:
Const request = require (". / request")
Then define the parser:
Const resolvers = {Query: {/ / Get all available prices async getPrices (parent, args, ctx, info) {const prices = await requests.getPrices (); return {price: prices.data};}, / / Get the price of a given currency symbol async getPrice (parent, args, ctx, info) {const prices = await requests.getPrices () Return {price: {[args ["currency"]]: prices.data [args ["currency"]}};}
Our parser has a root field, Query, within which we will define all parsers in GraphQL Schema. Notice that the names of these parsers are the same as in types.js.
Each parser is a function with four parameters:
Parent: parent object
Args: parameter
Ctx: context
Info: field-specific information
9. Server
Now that we have types, parsers, and aids, all we need to do is integrate.
Open the index.js file and enter the following:
Const {GraphQLServer} = require ("graphql-yoga"); const typeDefs = require (". / graphql/types.js"); const resolvers = require (". / graphql/resolvers.js"); const server = new GraphQLServer ({typeDefs, resolvers, context: {/ / if we pass anything here can be available in all resolvers}}); server.start (() = > console.log ("Server is running on localhost:4000 ☄"))
First, let's create a GraphQLServer instance:
... const server = new GraphQLServer ({typeDefs, resolvers, context: {/ / if we pass anything here can be available in all resolvers}});
Then run the instance:
Server.start () = > console.log ("Server is running on localhost:4000 ☄"))
After running, you can see the following output:
Server is running on localhost:4000 ☄
Now open a browser to access http://localhost:4000 and test the following query:
Query ($currency:String!) {getPrice (currency:$currency) {price}} # Variables: {"currency": "USD"}
The results are as follows:
At this point, I believe you have a deeper understanding of "how NodeJS and GraphQL realize the real-time Bitcoin market". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.