|
| 1 | +/** |
| 2 | + * Subscribes a user to a specific forum topic via GraphQL. |
| 3 | + * @param {Request} request - The incoming web request. |
| 4 | + * @param {Object} environment - The environment bindings (for API keys). |
| 5 | + * @returns {Promise<Response>} |
| 6 | + */ |
| 7 | +export default async function subscribeToTopic(request, environment) { |
| 8 | + const { searchParams } = new URL(request.url); |
| 9 | + const topicId = searchParams.get("topicId"); |
| 10 | + |
| 11 | + // 1. Validation |
| 12 | + if (!topicId) { |
| 13 | + return new Response(JSON.stringify({ error: "topicId is required" }), { |
| 14 | + status: 400, |
| 15 | + headers: { "Content-Type": "application/json" }, |
| 16 | + }); |
| 17 | + } |
| 18 | + |
| 19 | + try { |
| 20 | + // 2. Auth Retrieval |
| 21 | + const bearer = await environment.MYOSHI_CO_BAYLA_API_KEY.get(); |
| 22 | + |
| 23 | + // 3. GraphQL Request |
| 24 | + const gqlResponse = await fetch("https://api.myoshi.co/graphql", { |
| 25 | + method: "POST", |
| 26 | + headers: { |
| 27 | + "Content-Type": "application/json", |
| 28 | + Authorization: `Bearer ${bearer}`, |
| 29 | + }, |
| 30 | + body: JSON.stringify({ |
| 31 | + operationName: "SubscribeForumTopic", |
| 32 | + variables: { topicId }, |
| 33 | + extensions: { |
| 34 | + clientLibrary: { name: "@apollo/client", version: "4.1.2" }, |
| 35 | + }, |
| 36 | + query: ` |
| 37 | + mutation SubscribeForumTopic($topicId: ID!) { |
| 38 | + forums { |
| 39 | + subscribeTopic(topic_id: $topicId) { |
| 40 | + success |
| 41 | + errors { |
| 42 | + code |
| 43 | + message |
| 44 | + __typename |
| 45 | + } |
| 46 | + topic { |
| 47 | + id |
| 48 | + is_subscribed |
| 49 | + __typename |
| 50 | + } |
| 51 | + __typename |
| 52 | + } |
| 53 | + __typename |
| 54 | + } |
| 55 | + } |
| 56 | + `, |
| 57 | + }), |
| 58 | + }); |
| 59 | + |
| 60 | + const data = await gqlResponse.json(); |
| 61 | + |
| 62 | + // 4. Return Data |
| 63 | + return new Response(JSON.stringify(data), { |
| 64 | + status: gqlResponse.status, |
| 65 | + headers: { "Content-Type": "application/json" }, |
| 66 | + }); |
| 67 | + } catch (error) { |
| 68 | + // Basic error handling for network/runtime failures |
| 69 | + return new Response( |
| 70 | + JSON.stringify({ |
| 71 | + error: "Internal Server Error", |
| 72 | + details: error.message, |
| 73 | + }), |
| 74 | + { status: 500, headers: { "Content-Type": "application/json" } }, |
| 75 | + ); |
| 76 | + } |
| 77 | +} |
0 commit comments