在撰写此答案时,阿波罗无法做到这一点。唯一的解决方案是手动监控可用性并相应地利用 apollo。我用apollo-server-express
这个。
下面演示了我如何根据服务的可用性来利用我的 apollo 网关。
基本上,你包装了你的 apollo 服务器的中间件。这允许您交换您的 apollo 服务器实例,并在它们不可用时抛出错误。
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import bodyParser from 'body-parser'; // use express body-parser for convinience
// your list of federated services
const serviceList = [
{ name: 'service1', url: 'http://service1/graphql' }
];
// a variable to store the server. We will need to replace him when a service goes offline or comes back online again
let server = null;
// setup express
const app = express();
app.use(bodyParser.json());
app.use(customRouterToLeverageApolloServer); // defined below
// middleware to leverage apollo server
function customRouterToLeverageApolloServer(req, res, next) {
// if services are down (no apollo instance) throw an error
if(!server) {
res.json({ error: 'services are currently not available' });
return;
}
// else pass the request to apollo
const router = server.getMiddleware(); // https://www.apollographql.com/docs/apollo-server/api/apollo-server/#apolloservergetmiddleware
return router(req, res, next);
}
function servicesAreAvailable() {
// go through your serviceList and check availability
}
// periodically check the availability of your services and create/destroy an ApolloServer instance accordingly. This will also be the indication whether or not your services are available at the time.
// you might want to also call this function at startup
setInterval(() => {
if(servicesAreAvailable()) {
server = new ApolloServer({ ... });
}
else {
server = null;
}
}, 1000 * 60 * 5) // check every 5 minutes