Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Created July 23, 2023 12:38
Show Gist options
  • Save daichan4649/114d185eb42a3466f9452efc7ba5296c to your computer and use it in GitHub Desktop.
Save daichan4649/114d185eb42a3466f9452efc7ba5296c to your computer and use it in GitHub Desktop.
Nuxt3 (Express) + LINE Messaging API
// 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) // <- これがポイント
// 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