目前正在处理RESTAPI和GraphQL微服务的Express Gateway。GraphQL管道工作得很好,但RESTAPI的管道是我正在努力解决的问题。
我制作了一个简单的CRUD功能RESTAPI,它可以创建、读取、更新和删除书籍和作者。它们有多条路由来实现这一点,例如:http://localhost:4001/books/add。
问题是我并不真正理解如何在快速网关中转换这些路由或路径,以便通过网关到达它们。
这是我当前的代码,config.yml:
http:
port: 8080
admin:
port: 9876
host: localhost
apiEndpoints:
restapi:
host: localhost
paths: '/rp'
graphql:
host: localhost
paths: '/gql'
serviceEndpoints:
restapi:
url: 'http://localhost:4001/'
graphql:
url: 'http://localhost:4000'
policies:
- proxy
pipelines:
restapi:
apiEndpoints:
- restapi
policies:
- proxy:
- action:
serviceEndpoint: restapi
changeOrigin: true
ignorePath: false
prependPath: true
stripPath: true
graphql:
apiEndpoints:
- graphql
policies:
- proxy:
- action:
serviceEndpoint: graphql
changeOrigin: true
这是restapi书籍代码:
const express = require('express');
const mongoose = require('mongoose');
const book = require('../models/book');
const { findById } = require('../models/book');
const router = express.Router();
const Book = require('../models/book');
//read all books
router.get('/', async (req, res) =>{
try{
const AllBooks = await Book.find();
res.json(AllBooks);
}catch(err){
res.json({message:err});
}
})
//create book
router.post('/add', async (req, res) => {
var NewBook = new Book({
title: req.body.title,
pages: req.body.pages
})
try{
const SavedBook = await NewBook.save();
res.json(SavedBook);
}catch(err){
res.json({message: err})
}
})
//read book
router.get('/:BookId', async (req, res) => {
try{
const ReadBook = await Book.findById(req.params.BookId);
res.json(ReadBook);
}catch(err){
res.json({message: err});
}
})
//update book
router.patch('/update/:BookId', async (req, res) => {
try{
const updatedBook = await Book.updateOne({_id: req.params.BookId},
{$set: {title: req.body.title, pages: req.body.pages}});
res.json(updatedBook);
}catch(err){
res.json({message: err});
}
})
//delete book
router.delete('/delete/:BookId', async (req, res) => {
try{
const DelBook = await Book.findById(req.params.BookId);
DelBook.delete();
res.send(DelBook + " Deleted");
}catch(err){
res.json({message: err});
}
})
module.exports = router;
现在,当我调用:http://localhost:4001/rp时,它返回“restapi”,就像我告诉的那样。但是当我调用:http://localhost:4001/rp/books时,它返回一个“无法获取”,这是我没有定义此路径的逻辑原因。首先,我认为快速网关会自动理解这一点。
我必须硬编码所有的路径吗?
我希望有人能向我解释,因为express gateway没有象我这样的例子。:)
我找到了解决办法。
我对apiEndpoint和ServiceEndpoint之间的定义感到困惑。
答案是:是的,您必须硬编码所有路径,但这将只在“apiendpoints”下。
它将看起来是这样的:
apiEndpoints:
restapi:
host: localhost
paths:
- '/books'
- '/books/add'
- '/authors'
- '/authors/...'
serviceEndpoints:
restapi:
url: 'http://localhost:4001'
因此,总而言之,只有一个带有多个api端点的服务,这听起来很合乎逻辑。
我认为一个缺点是,当有很多服务时,这个配置文件会变成一大堆端点。