Created
July 23, 2023 12:38
-
-
Save daichan4649/114d185eb42a3466f9452efc7ba5296c to your computer and use it in GitHub Desktop.
Nuxt3 (Express) + LINE Messaging API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server_express/api/line.ts | |
import { ClientConfig, Client, middleware, MiddlewareConfig, WebhookEvent, TextMessage, } from '@line/bot-sdk' | |
const channelAccessToken = process.env.CHANNEL_ACCESS_TOKEN || '' | |
const channelSecret = process.env.CHANNEL_SECRET || '' | |
const clientConfig: ClientConfig = { | |
channelAccessToken, | |
channelSecret, | |
} | |
const middlewareConfig: MiddlewareConfig = { | |
channelAccessToken, | |
channelSecret | |
} | |
const client = new Client(clientConfig) | |
// express | |
import express, { Application, Request, Response } from 'express' | |
const app: Application = express() | |
app.post("/webhook", | |
middleware(middlewareConfig), | |
async (req: Request, res: Response,) => { | |
const events: WebhookEvent[] = req.body.events | |
const results = await Promise.all( | |
events.map(async (event: WebhookEvent) => { | |
return handleMessageEvent(event) | |
}) | |
) | |
return res.status(200).json({ | |
status: 'success', | |
results, | |
}) | |
} | |
) | |
const handleMessageEvent = async (event: WebhookEvent) => { | |
if (event.type === 'message' && event.message.type === 'text') { | |
const replyMessage: TextMessage = { type: 'text',text } | |
return client.replyMessage(replyToken, replyMessage) | |
} | |
・・・ | |
} | |
export default fromNodeMiddleware(app) // <- これがポイント |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// nuxt.config.ts | |
export default defineNuxtConfig({ | |
serverHandlers: [ | |
{ | |
route: '/api/line', | |
middleware: true, | |
handler: '~/server_express/api/line.ts' | |
}, | |
], | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment