Kuidas luua lõõskavat kiiret GraphQL API-d Node.js, MongoDB ja Fastify abil

See õpetus on neljaosalise seeria teine ​​osa, mille eesmärk on viia teid nullist täisfunktsionaalse täispika rakenduse juurutamiseni .

  • 1. osa: Kuidas luua lõõskavaid kiireid REST-i API-sid Node.js, MongoDB, Fastify ja Swagger abil
  • 2. osa: Kuidas luua lõõskavat kiiret GraphQL API-d Node.js, MongoDB, Fastify ja GraphQL abil! (Sa oled siin.)
  • 3. osa: Vue.js ühendamine GraphQL API-ga .
  • 4. osa: GraphQL API ja Vue.js esiplaani rakenduse juurutamine .

Seeria esimene osa on saadaval siin ja rakenduse lähtekoodi leiate siit.

Selles osas vaatame mudeleid , kontrollereid ja marsruute uuesti esimesest osast ning integreerime seejärel GraphQL rakendusse. Boonusena kasutame ka Faker.js-ivõltsandmete loomiseks ja andmebaasi loomiseks .

Sissejuhatus:

GraphQL on API-de päringukeel ja käitamisaeg nende päringute täitmiseks teie olemasolevate andmetega.

Iga GraphQL-i päring läbib kolm faasi: päringud on sõelutud, valideeritud ja täidetud.

GraphQL pakub teie API-s olevate andmete täielikku ja arusaadavat kirjeldust, annab klientidele õiguse küsida täpselt seda, mida nad vajavad, muudab API-de aja jooksul lihtsamaks arendamise ja võimaldab võimsaid arendaja tööriistu. Lisateave.

Eeldused…

Kui olete selle sarja esimese osa valmis saanud, peaksite olema kursis algajate / kesktaseme JavaScripti teadmistega, Node.js, Fastify.JS ja MongoDB (Mongoose).

Jätkamiseks peate täitma selle sarja ühe osa või haarama koodi Gitilt, kuigi ma soovitaksin tungivalt vähemalt esimese osa läbi vaadata.

Alustame!

Kloonige esimese osa repo (jätke see samm vahele, kui järgisite esimest osa ja jätkate oma koodiga), avades terminali, navigeerides oma projekti kataloogi jatäidetakse iga järgmine koodirida:

git clone //github.com/siegfriedgrimbeek/fastify-api.git cd fastify-api

Nüüd, kui meil on koodibaasi koopia, värskendame oma pakette ja package.jsonfaili, käivitades järgmise koodi:

sudo npm i -g npm-check-updates ncu -u npm install

Kõigepealt installime globaalselt npm paketi „ npm-check-updates ” ja seejärel kasutame seda paketti, et oma package.jsonfaili automaatselt värskendada uusimate paketiversioonidega ja seejärel installime / värskendame kõiki oma npm mooduleid käivitades npm install.

Seda tehakse tagamaks, et kõik õpetuse lõpetajad töötaksid samade paketiversioonidega.

Refactor meie server ja käivitage rakendus!

Nagu kõigi tarkvaralahendusi, kui lahendus kasvab, arendajad sageli vaja uuesti ja Refactor koodi.

Aastal srckataloog loome uue faili nimega server.js:

cd src touch server.js

Lisage server.jsfaili järgmine kood :

// Require the fastify framework and instantiate it const fastify = require('fastify')({ logger: true }) // Require external modules const mongoose = require('mongoose') // Connect to DB mongoose .connect('mongodb://localhost/mycargarage') .then(() => console.log('MongoDB connected...')) .catch(err => console.log(err)) module.exports = fastify

Oleme nüüd kaevandatud loogika, et alustab server on server.jsfail, mis võimaldab meil uuesti seda koodi kogu projekti.

Järgmisena peame oma index.jsfaili srckataloogis värskendama :

 // Import Server const fastify = require('./server.js') // Import Routes const routes = require('./routes') // Import Swagger Options const swagger = require('./config/swagger') // Register Swagger fastify.register(require('fastify-swagger'), swagger.options) // Loop over each route routes.forEach((route, index) => { fastify.route(route) }) // Run the server! const start = async () => { try { await fastify.listen(3000, '0.0.0.0') fastify.swagger() fastify.log.info(`server listening on ${fastify.server.address().port}`) } catch (err) { fastify.log.error(err) process.exit(1) } } start()

index.jsPärast GraphQL-i seadistamist ja konfigureerimist vaatame faili uuesti üle .

Käivitage server Fastify , käivitades oma terminalis järgmise koodi :

npm start

Pange tähele, et marsruudi vaikeseadistust pole, nii et praegu navigeerimisel saidile // localhost: 3000 / tagastab server 404 tõrke, mis on õige.

Käivitage MongoDB ja värskendage mudeleid

Laiendame olemasolevat mudelit, et see hõlmaks ka teenuseid ja omanikke. Allpool olev diagramm näitab seoseid kogude vahel:

  • Ühel autol võib olla üks omanik.
  • Ühel omanikul võib olla palju autosid.
  • Ühel autol võib olla palju teenuseid.

Vaadake kataloogis uuesti Car.jsfaili modelsja värskendage seda järgmiselt:

// External Dependancies const mongoose = require("mongoose") const ObjectId = mongoose.Schema.Types.ObjectId const carSchema = new mongoose.Schema({ title: String, brand: String, price: String, age: Number, owner_id: ObjectId }) module.exports = mongoose.model("Car", carSchema)

Loo kaks uut failide modelskataloog, Owner.js ja Service.jslisada järgmine kood failid vastavalt:

Owner.js

// External Dependancies const mongoose = require('mongoose') const ownerSchema = new mongoose.Schema({ firstName: String, lastName: String, email: String }) module.exports = mongoose.model('Owner', ownerSchema)

Service.js

// External Dependancies const mongoose = require("mongoose") const ObjectId = mongoose.Schema.Types.ObjectId const serviceSchema = new mongoose.Schema({ car_id: ObjectId, name: String, date: String }) module.exports = mongoose.model("Service", serviceSchema) view rawService.js hosted with ❤ by GitHub

Ülalnimetatud koodis pole kasutatud uusi mõisteid. Oleme just loonud standardsed Mongoose skeemid, nagu ka Car.jsmudeli puhul.

Vaadake uuesti autojuhti ja looge täiendavad kontrollerid

Leidub pisut muutunud carController.jsnii Liigu controllerskataloogi ja värskendada oma faili kohta allpool:

// External Dependancies const boom = require('boom') // Get Data Models const Car = require('../models/Car') // Get all cars exports.getCars = async () => { try { const cars = await Car.find() return cars } catch (err) { throw boom.boomify(err) } } // Get single car by ID exports.getSingleCar = async req => { try { const id = req.params === undefined ? req.id : req.params.id const car = await Car.findById(id) return car } catch (err) { throw boom.boomify(err) } } // Add a new car exports.addCar = async req => { try { const car = new Car(req) const newCar = await car.save() return newCar } catch (err) { throw boom.boomify(err) } } // Update an existing car exports.updateCar = async req => { try { const id = req.params === undefined ? req.id : req.params.id const updateData = req.params === undefined ? req : req.params const update = await Car.findByIdAndUpdate(id, updateData, { new: true }) return update } catch (err) { throw boom.boomify(err) } } // Delete a car exports.deleteCar = async req => { try { const id = req.params === undefined ? req.id : req.params.id const car = await Car.findByIdAndRemove(id) return car } catch (err) { throw boom.boomify(err) } }

Looge controllerskataloogis kaks uut faili serviceController.jsja ownerController.jsja lisage failidele järgmine kood:

serviceController.js

// External Dependancies const boom = require('boom') // Get Data Models const Service = require('../models/Service') // Get single service ID exports.getSingleService = async req => { try { const id = req.params === undefined ? req.id : req.params.id const service = await Service.findById(id) return service } catch (err) { throw boom.boomify(err) } } // Get single car's services exports.getCarsServices = async req => { try { const id = req.params === undefined ? req.id : req.params.id const services = await Service.find({ car_id: id }) return services } catch (err) { throw boom.boomify(err) } }

ownerController.js

// External Dependancies const boom = require('boom') // Get Data Models const Owner = require('../models/Owner') const Car = require('../models/Car') // Get all owners exports.getOwner = async () => { try { const owners = await Owner.find() return owners } catch (err) { throw boom.boomify(err) } } // Get single owner by ID exports.getSingleOwner = async req => { try { const id = req.params === undefined ? req.id : req.params.id const owner = await Owner.findById(id) return owner } catch (err) { throw boom.boomify(err) } } // Get single owner's cars exports.getOwnersCars = async req => { try { const id = req.params === undefined ? req.id : req.params.id const cars = await Car.find({ owner_id: id }) return cars } catch (err) { throw boom.boomify(err) } }

Kontrollerite suurim muutus on see, kuidas me parameetreid saame:

const id = req.params === undefined ? req.id : req.params.id const updateData = req.params === undefined ? req : req.params

Eespool nimetatud koodi nimetatakse " tingimuslik (kolmekomponendiliste) operaator " ja seda kasutatakse tinglikult järgmis kui avaldus:

let id if (req.params === undefined) { id = req.id } else { id = req.params.id }

Kasutame kolmekordset operaatorit nii REST API kui ka GraphQL API päringute rahuldamiseks , kuna nende rakendus on veidi erinev.

Aeg külvata andmebaas võltsandmetega!

In the src directory let’s create a new directory and file by running the following code:

mkdir helpers touch seed.js

Add the following code to the seed.js file:

 // Import external dependancies const faker = require('faker') const boom = require('boom') // Import internal dependancies const fastify = require('../server.js') // Fake data const cars = [ { name: 'Tesla', models: ['S', 'E', 'X', 'Y'] }, { name: 'Mercedes', models: ['GLA', 'GLC', 'GLE', 'GLS'] }, { name: 'BMW', models: ['X4', 'Z3', 'M2', '7'] }, { name: 'Audi', models: ['A1', 'A3', 'A4', 'A5'] }, { name: 'Ford', models: ['Fiesta', 'Focus', 'Fusion', 'Mustang'] } ] const serviceGarages = ['A++ Auto Services', "Gary's Garage", 'Super Service', 'iGarage', 'Best Service'] // Get Data Models const Car = require('../models/Car') const Owner = require('../models/Owner') const Service = require('../models/Service') // Fake data generation functions const generateOwnerData = () => { let ownerData = [] let i = 0 while (i  { let carData = [] let i = 0 while (i  { let serviceData = [] let i = 0 while (i  { try { const owners = await Owner.insertMany(generateOwnerData()) const ownersIds = owners.map(x => x._id) const cars = await Car.insertMany(generateCarData(ownersIds)) const carsIds = cars.map(x => x._id) const services = await Service.insertMany(generateServiceData(carsIds)) console.log(` Data successfully added: - ${owners.length} owners added. - ${cars.length} cars added. - ${services.length} services added. `) } catch (err) { throw boom.boomify(err) } process.exit() }, err => { console.log('An error occured: ', err) process.exit() } )

Let’s break down this mountain of code:

First we import two external libraries, Faker.jswhich is used to generate fake data and Boom, which is used to throw http friendly error objects.

Then we import the server.js file which will spin up an instance of our server allowing us to interact with the models.

We then declare two arrays with fake data, cars and serviceGarages.

Then we import the models and declare three functions (generateOwnerData, generateCarData, generateServiceData) which each return an array of objects with the owner, car and service data respectively.

Once the Fastify.js instance is ready we use the Mongoose insertMany() function to insert the generated arrays into the database. The function then returns an array of objects containing the original object data and ids of the each record.

We use the JavaScript Map function to create an array of idsowners and cars arrays. We use the ownersIDs array for when generating car data and we use the carsIds array when generating service data, they are passed into the respective functions and then values are randomly selected from them.

Lastly we need to install the Faker.js package and add the seed task to our package.json file.

We can add the Faker.js package by navigating to the root directory and running the following code:

npm i faker -D

We then add the following to the package.json file:

... "scripts": { ... "seed": "node ./src/helpers/seed.js" }, ...

That’s it! We can now run our seeding script from the project root directory with the following code:

npm run seed

If you are using MongoDB Compass (you should), you will see the data in your database:

GraphQL installation, setup and testing

Let’s get started by navigating to the root directory and running the following code:

npm i fastify-gql graphql

The above installs GraphQL and the Fastify barebone GraphQL adapter.

Navigate to the src directory and run the following code:

mkdir schema cd shema touch index.js

Navigate to the src directory update the index.js file with the following:

// Import Server const fastify = require('./server.js') // Import external dependancies const gql = require('fastify-gql') // Import GraphQL Schema const schema = require('./schema') // Register Fastify GraphQL fastify.register(gql, { schema, graphiql: true }) ... end here // Import Routes const routes = require('./routes')

With the above code we require the Fastify GraphQL Adapter, import the schema and register the GraphQl Adapter with Fastify.

We register the schema and enable GraphiQL, an in-browser IDE for exploring GraphQL.

Navigate to the schema directory and open the index.js file and add the following boilerplate code:

// Import External Dependancies const graphql = require('graphql') // Destructure GraphQL functions const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLList, GraphQLNonNull } = graphql // Import Controllers const carController = require('../controllers/carController') const ownerController = require('../controllers/ownerController') const serviceController = require('../controllers/serviceController') // Define Object Types const carType = new GraphQLObjectType({ name: 'Car', fields: () => ({}) }) const ownerType = new GraphQLObjectType({ name: 'Owner', fields: () => ({}) }) const serviceType = new GraphQLObjectType({ name: 'Service', fields: () => ({}) }) // Define Root Query const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { car: {}, cars: {}, owner: {}, service: {} } }) // Define Mutations const Mutations = new GraphQLObjectType({ name: 'Mutations', fields: { addCar: { type: carType, args: {}, async resolve(args) { return '' } }, editCar: { type: carType, args: {}, async resolve(args) { return '' } }, deleteCar: { type: carType, args: {}, async resolve(args) { return '' } } } }) // Export the schema module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutations })

Let’s run through the above code:

We require the main GraphQL package and use JavaScript Destructuring to get the necessary GraphQL functions(GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLID, GraphQLList and GraphQLNonNull).

We import our three controllers (carController, ownerController and serviceController).

We declare the carType, ownerType and serviceTypeGraphQL Object Types, which are functions that accept an object as a parameter, with a name and a fields key.

These functions are used to define our GraphQL schema, similar to the Mongoose models defined earlier.

The fields can return a particular type, and methods that take arguments. Learn More about Object Types.

Then we declare the RootQuery which is also a GraphQL Object Type and is found at the top level of every GraphQL server. It represents all of the possible entry points into the GraphQL API. Learn More about root fields and resolvers.

We then declare our Mutations, which are used to change data. Although any query could be implemented to change data, operations that cause changes should be sent explicitly via a mutation. Learn More about Mutations.

Lastly we export the GraphQLSchema.

Now that we have our template setup we can start populating the Object Types, Root Query and Mutations.

Note that there are Mongoose to GraphQL schema generators available, but for the tutorial purposes we will manually create the schema.

Let’s update the carTypeObject Type as follows:

const carType = new GraphQLObjectType({ name: 'Car', fields: () => ({ _id: { type: GraphQLID }, title: { type: GraphQLString }, brand: { type: GraphQLString }, price: { type: GraphQLString }, age: { type: GraphQLInt }, owner_id: { type: GraphQLID }, owner: { type: ownerType, async resolve(parent, args) { return await ownerController.getSingleOwner({ id: parent.owner_id }) } }, services: { type: new GraphQLList(serviceType), async resolve(parent, args) { return await serviceController.getCarsServices({ id: parent._id }) } } }) })

Let’s dive deeper into the GraphQL functions, starting with the Scalars types in GraphQL:

GraphQL comes with a set of default scalar types out of the box:

  • Int: A signed 32‐bit integer. GraphQLInt
  • Float: A signed double-precision floating-point value. GraphQLFloat
  • String: A UTF‐8 character sequence. GraphQLString
  • Boolean: true or false. GraphQLBoolean
  • ID: The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialised in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable. GraphQLID

The owner and service fields are where it gets interesting. These fields are not defined as Scalar types like the rest — instead, their type is referencing the ownerType and serviceType that we have created and are yet to populate.

Teine argument, mille me väljadele ownerja edastame, serviceon resolverfunktsioonid.

Resolveri funktsioonid või meetodid on funktsioonid, mis lahendavad skeemi tüübi või välja väärtuse

Ka resolverid võivad olla asünkroonsed! Nad saavad lahendada väärtusi teisest REST API-st, andmebaasist, vahemälust, konstandist jne.

Võite mõelda GraphQL päringu igale väljale kui eelmise tüüpi funktsioonile või meetodile, mis tagastab järgmise tüübi. Tegelikult töötab GraphQL täpselt nii. Iga tüübi iga välja taga on funktsioon nimega resolver, mille pakub GraphQL-i serveri arendaja. Kui väli on täidetud, kutsutakse vastav resolver järgmise väärtuse loomiseks.

If a field produces a scalar value like a string or number, then the execution completes. However if a field produces an object value then the query will contain another selection of fields which apply to that object. This continues until scalar values are reached. GraphQL queries always end at scalar values.

In order to create the relationship between the different types we pass the _id and the owner_id values into the respective controller functions.

So essentially we are requesting the owner details along with the car details:

return await userController.getSingleOwner({ id: parent.owner_id })

and the details of all the services related to the car:

return await serviceController.getCarsServices({ id: parent._id })

To return a list or array from with GraphQL, we use the GraphQLList. Here is a great in depth tutorial about using arrays in GraphQL Schema, but it is really simple: whenever we need an array we will use the GraphQLList function.

Let’s update the ownerType and serviceType with the following code:

ownerType

const ownerType = new GraphQLObjectType({ name: 'Owner', fields: () => ({ _id: { type: GraphQLID }, firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, email: { type: GraphQLString }, cars: { type: new GraphQLList(carType), async resolve(parent, args) { return await ownerController.getOwnersCars({ id: parent._id }) } } }) })

serviceType

const serviceType = new GraphQLObjectType({ name: 'Service', fields: () => ({ _id: { type: GraphQLID }, car_id: { type: GraphQLID }, name: { type: GraphQLString }, date: { type: GraphQLString }, car: { type: carType, async resolve(parent, args) { return await carController.getSingleCar({ id: parent.car_id }) } } }) })

The above two Object Types are very similar to the carType. You can notice a pattern between the different Object Types and their relationships.

We can now populate the RootQuery root with the following code:

const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { car: { type: carType, args: { id: { type: GraphQLID } }, async resolve(parent, args) { return await carController.getSingleCar(args) } }, cars: { type: new GraphQLList(carType), async resolve(parent, args) { return await carController.getCars() } }, owner: { type: ownerType, args: { id: { type: GraphQLID } }, async resolve(parent, args) { return await ownerController.getSingleOwner(args) } }, service: { type: serviceType, args: { id: { type: GraphQLID } }, async resolve(parent, args) { return await serviceController.getSingleService(args) } } } })

There are no new concepts in the above code, but keep in mind that the RootQuery query is the entry point to all queries on the GraphQL API. So from the above we can see that we can run the following queries directly:

  • Get all the Cars
  • Get a single Car
  • Get a single Owner
  • Get a single Service

Let’s open the GraphiQL user interface and build some queries: //localhost:3000/graphiql.html

Queries are entered on the left, results are in the middle, and the documentation explorer is on the right.

The documentation explorer can be used to explore the entire graph down to Scalar level. This is very helpful when building queries.

The language used to build the queries resembles JSON. This cheat sheet is a great a reference.

Below demonstrates why GraphQL is so awesome:

In the above example, we are using the cars root query to display a list of all the cars, their owners, and their services.

We have one final topic to address, and that is mutations. Let’s update the mutations with the following code:

const Mutations = new GraphQLObjectType({ name: 'Mutations', fields: { addCar: { type: carType, args: { title: { type: new GraphQLNonNull(GraphQLString) }, brand: { type: new GraphQLNonNull(GraphQLString) }, price: { type: GraphQLString }, age: { type: GraphQLInt }, owner_id: { type: GraphQLID } }, async resolve(parent, args) { const data = await carController.addCar(args) return data } }, editCar: { type: carType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, title: { type: new GraphQLNonNull(GraphQLString) }, brand: { type: new GraphQLNonNull(GraphQLString) }, price: { type: new GraphQLNonNull(GraphQLString) }, age: { type: new GraphQLNonNull(GraphQLInt) }, owner_id: { type: GraphQLID } }, async resolve(parent, args) { const data = await carController.updateCar(args) return data } }, deleteCar: { type: carType, args: { id: { type: new GraphQLNonNull(GraphQLID) } }, async resolve(parent, args) { const data = await carController.deleteCar(args) return data } } } })

As before, we declare our Object Type, specify the name and the fields.

A mutation consists of the the type, args and the async resolve function. The resolve function passes the args to the controller, which returns the result of the mutation.

Nüüd olete kodeerinud täisfunktsionaalse REST API ja täisfunktsionaalse GraphQL API.

Puuduvad reeglid, mille kohaselt peaks kasutama ainult REST või ainult GraphQL. Mõnes projektis võib parim lahendus olla segu mõlemast. See määratakse tegelikult projektide vahel.

Lähtekoodi vormi Git saate alla laadida siit.

Mis on järgmine?

Järgmises õpetuses tarbime oma GraphQL API koos Vue.js esiplaaniga ühe lehe rakendusena!