【发布时间】:2020-07-02 18:30:29
【问题描述】:
我有一个 graphql 服务器,我想为其添加一个自定义端点,以便当客户的订阅状态发生变化时,Stripe 可以与其通信。
目前,我的 index.js 文件看起来像一个典型的 Apollo 服务器设置:
import { ApolloServer } from "apollo-server";
import { connectDb } from "./models";
import schema from "./schema";
import resolvers from "./resolvers";
import contexts from "./contexts";
const server = new ApolloServer({
typeDefs: schema,
resolvers,
context: async ({ req }) => {
const { getCurrentUser } = contexts;
const currentUser = await getCurrentUser(req);
return { models, currentUser };
},
});
connectDb().then(async () => {
server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
console.log(`???? Server ready at ${url}`);
});
});
所以只有/graphql 暴露了。
如何添加一个自定义的POST /foobar 端点来做类似的事情? (来源:https://stripe.com/docs/webhooks/build#example-code)
// This example uses Express to receive webhooks
const app = require('express')();
// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');
// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
let event;
try {
event = JSON.parse(request.body);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
// Then define and call a method to handle the successful payment intent.
// handlePaymentIntentSucceeded(paymentIntent);
break;
case 'payment_method.attached':
const paymentMethod = event.data.object;
// Then define and call a method to handle the successful attachment of a PaymentMethod.
// handlePaymentMethodAttached(paymentMethod);
break;
// ... handle other event types
default:
// Unexpected event type
return response.status(400).end();
}
// Return a response to acknowledge receipt of the event
response.json({received: true});
});
app.listen(8000, () => console.log('Running on port 8000'));
【问题讨论】:
标签: node.js graphql apollo-server