Skip to content

Commit 731c80f

Browse files
committed
03 Add ESM test project
1 parent c3a665a commit 731c80f

File tree

8 files changed

+1621
-1
lines changed

8 files changed

+1621
-1
lines changed

.github/workflows/test.yml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,17 @@ jobs:
4646
run: export NODE_OPTIONS=--openssl-legacy-provider; npm run apidocs
4747
- name: Test building docs
4848
run: export NODE_OPTIONS=--openssl-legacy-provider; npm run docs:build
49-
- name: Test building examples
49+
- name: Test building examples (CJS)
5050
run: |
5151
cd examples/echo-bot-ts
5252
npm run build-sdk
5353
npm install
5454
npm run build
5555
cd -
56+
- name: Test building examples (ESM)
57+
run: |
58+
cd examples/echo-bot-ts-esm
59+
npm run build-sdk
60+
npm install
61+
npm run build
62+
cd -
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Dependencies
2+
node_modules/
3+
4+
# Built files.
5+
dist/

examples/echo-bot-ts-esm/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# LINE Echo Bot with TypeScript (ESM)
2+
3+
An example LINE bot to echo message with TypeScript. The bot is coded according to TypeScript's best practices.
4+
5+
## Prerequisite
6+
7+
- Git
8+
- Node.js version 10 and up
9+
- LINE Developers Account for the bot
10+
11+
## Installation
12+
13+
- Clone the repository.
14+
15+
```bash
16+
git clone https://github.com/line/line-bot-sdk-nodejs.git
17+
```
18+
19+
- Change directory to the example.
20+
21+
```bash
22+
cd line-bot-sdk-nodejs/examples/echo-bot-ts
23+
```
24+
25+
- Install all dependencies.
26+
27+
```bash
28+
npm run build-sdk
29+
npm install
30+
```
31+
32+
- Configure all the environment variables.
33+
34+
```bash
35+
export CHANNEL_ACCESS_TOKEN=<YOUR_CHANNEL_ACCESS_TOKEN>
36+
export CHANNEL_SECRET=<YOUR_CHANNEL_SECRET>
37+
export PORT=<YOUR_PORT>
38+
```
39+
40+
- Set up your webhook URL in your LINE Official Account to be in the following format. Don't forget to disable the greeting messages and auto-response messages for convenience.
41+
42+
```bash
43+
https://example.com/callback
44+
```
45+
46+
- Compile the TypeScript files.
47+
48+
```bash
49+
npm run build
50+
```
51+
52+
- Run the application.
53+
54+
```bash
55+
npm start
56+
```
57+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
declare global {
2+
namespace NodeJS {
3+
interface ProcessEnv {
4+
CHANNEL_ACCESS_TOKEN: string;
5+
CHANNEL_SECRET: string;
6+
PORT: string;
7+
}
8+
}
9+
}
10+
11+
export {};

examples/echo-bot-ts-esm/index.ts

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// Import all dependencies, mostly using destructuring for better view.
2+
import {
3+
ClientConfig,
4+
MessageAPIResponseBase,
5+
messagingApi,
6+
middleware,
7+
MiddlewareConfig,
8+
webhook,
9+
HTTPFetchError,
10+
} from '@line/bot-sdk';
11+
import express, {Application, Request, Response} from 'express';
12+
13+
// Setup all LINE client and Express configurations.
14+
const clientConfig: ClientConfig = {
15+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN || '',
16+
};
17+
18+
const middlewareConfig: MiddlewareConfig = {
19+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
20+
channelSecret: process.env.CHANNEL_SECRET || '',
21+
};
22+
23+
const PORT = process.env.PORT || 3000;
24+
25+
// Create a new LINE SDK client.
26+
const client = new messagingApi.MessagingApiClient(clientConfig);
27+
28+
// Create a new Express application.
29+
const app: Application = express();
30+
31+
const isTextEvent = (event: any): event is webhook.MessageEvent & { message: webhook.TextMessageContent } => {
32+
return event.type === 'message' && event.message && event.message.type === 'text';
33+
};
34+
35+
// Function handler to receive the text.
36+
const textEventHandler = async (event: webhook.Event): Promise<MessageAPIResponseBase | undefined> => {
37+
// Process all variables here.
38+
if (!isTextEvent(event)) {
39+
return;
40+
}
41+
42+
// Process all message related variables here.
43+
// Create a new message.
44+
// Reply to the user.
45+
await client.replyMessage({
46+
replyToken: event.replyToken as string,
47+
messages: [{
48+
type: 'text',
49+
text: event.message.text,
50+
}],
51+
});
52+
};
53+
54+
// Register the LINE middleware.
55+
// As an alternative, you could also pass the middleware in the route handler, which is what is used here.
56+
// app.use(middleware(middlewareConfig));
57+
58+
// Route handler to receive webhook events.
59+
// This route is used to receive connection tests.
60+
app.get(
61+
'/',
62+
async (_: Request, res: Response): Promise<Response> => {
63+
return res.status(200).json({
64+
status: 'success',
65+
message: 'Connected successfully!',
66+
});
67+
}
68+
);
69+
70+
// This route is used for the Webhook.
71+
app.post(
72+
'/callback',
73+
middleware(middlewareConfig),
74+
async (req: Request, res: Response): Promise<Response> => {
75+
const callbackRequest: webhook.CallbackRequest = req.body;
76+
const events: webhook.Event[] = callbackRequest.events!;
77+
78+
// Process all the received events asynchronously.
79+
const results = await Promise.all(
80+
events.map(async (event: webhook.Event) => {
81+
try {
82+
await textEventHandler(event);
83+
} catch (err: unknown) {
84+
if (err instanceof HTTPFetchError) {
85+
console.error(err.status);
86+
console.error(err.headers.get('x-line-request-id'));
87+
console.error(err.body);
88+
} else if (err instanceof Error) {
89+
console.error(err);
90+
}
91+
92+
// Return an error message.
93+
return res.status(500).json({
94+
status: 'error',
95+
});
96+
}
97+
})
98+
);
99+
100+
// Return a successful message.
101+
return res.status(200).json({
102+
status: 'success',
103+
results,
104+
});
105+
}
106+
);
107+
108+
// Create a server and listen to it.
109+
app.listen(PORT, () => {
110+
console.log(`Application is live and listening on port ${PORT}`);
111+
});

0 commit comments

Comments
 (0)