big*_*ato 3 node.js graphql apollo-server
我有一个 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}`);
});
});
Run Code Online (Sandbox Code Playgroud)
所以只能/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'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2020 次 |
| 最近记录: |