Skip to content

Commit 4c4ea9c

Browse files
Yang-33tokuhirom
andauthored
Update example and document for ESM (#810)
Changes - Rewrite document in ESM - Add ESM example(almost same as CJS example) --------- Co-authored-by: Tokuhiro Matsuno <tokuhirom@gmail.com>
1 parent 20dd1e1 commit 4c4ea9c

File tree

11 files changed

+883
-53
lines changed

11 files changed

+883
-53
lines changed

docs/.vitepress/config.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ export default {
2020
{ text: 'Guide', link: '/guide.html' },
2121
{ text: 'API Reference', link: '/apidocs/modules.html' },
2222
{ text: 'Contributing', link: '/CONTRIBUTING.html' },
23-
{ text: 'LINE Developers', link: 'https://developers.line.biz/en/' },
2423
{ text: 'GitHub', link: 'https://github.com/line/line-bot-sdk-nodejs/' },
2524
],
2625
// Sidebar items

docs/getting-started/basic-usage.md

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
# Basic Usage
22

33
It can be imported with [CommonJS](https://nodejs.org/docs/latest/api/modules.html),
4-
[ES2015 modules](https://babeljs.io/learn-es2015/#ecmascript-2015-features-modules),
4+
[ECMAScript modules(ES modules)](https://tc39.es/ecma262/#sec-modules),
55
and preferably [TypeScript](https://www.typescriptlang.org/).
66

77
The library is written in TypeScript and includes TypeScript definitions by
88
default. Nevertheless, it can surely be used with plain JavaScript too.
99

1010
``` js
11+
// ES Modules or TypeScript
12+
import * as line from '@line/bot-sdk';
13+
1114
// CommonJS
1215
const line = require('@line/bot-sdk');
13-
14-
// ES2015 modules or TypeScript
15-
import * as line from '@line/bot-sdk';
1616
```
1717

1818
## Configuration
@@ -26,7 +26,6 @@ new line.messagingApi.MessagingApiClient({
2626
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
2727
});
2828
line.middleware({
29-
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
3029
channelSecret: 'YOUR_CHANNEL_SECRET'
3130
});
3231
```
@@ -36,39 +35,57 @@ line.middleware({
3635
Here is a synopsis of echoing webhook server with [Express](https://expressjs.com/):
3736

3837
``` js
39-
const express = require('express');
40-
const line = require('@line/bot-sdk');
38+
import * as line from '@line/bot-sdk'
39+
import express from 'express'
4140

41+
// create LINE SDK config from env variables
4242
const config = {
43-
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
44-
channelSecret: 'YOUR_CHANNEL_SECRET'
43+
channelSecret: process.env.CHANNEL_SECRET,
4544
};
4645

46+
// create LINE SDK client
47+
const client = new line.messagingApi.MessagingApiClient({
48+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN
49+
});
50+
51+
// create Express app
52+
// about Express itself: https://expressjs.com/
4753
const app = express();
48-
app.post('/webhook', line.middleware(config), (req, res) => {
54+
55+
// register a webhook handler with middleware
56+
// about the middleware, please refer to doc
57+
app.post('/callback', line.middleware(config), (req, res) => {
4958
Promise
5059
.all(req.body.events.map(handleEvent))
51-
.then((result) => res.json(result));
60+
.then((result) => res.json(result))
61+
.catch((err) => {
62+
console.error(err);
63+
res.status(500).end();
64+
});
5265
});
5366

54-
const client = new line.messagingApi.MessagingApiClient({
55-
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
56-
});
67+
// event handler
5768
function handleEvent(event) {
5869
if (event.type !== 'message' || event.message.type !== 'text') {
70+
// ignore non-text-message event
5971
return Promise.resolve(null);
6072
}
6173

74+
// create an echoing text message
75+
const echo = { type: 'text', text: event.message.text };
76+
77+
// use reply API
6278
return client.replyMessage({
6379
replyToken: event.replyToken,
64-
messages: [{
65-
type: 'text',
66-
text: event.message.text
67-
}],
80+
messages: [echo],
6881
});
6982
}
7083

71-
app.listen(3000);
84+
// listen on port
85+
const port = process.env.PORT || 3000;
86+
app.listen(port, () => {
87+
console.log(`listening on ${port}`);
88+
});
7289
```
7390

7491
The full examples with comments can be found

docs/guide/client.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,15 @@ For type signatures of the methods, please refer to [its API reference](../apido
1010
The `MessagingApiClient` class is provided by the main module.
1111

1212
``` js
13-
// CommonJS
14-
const MessagingApiClient = require('@line/bot-sdk').messagingApi.MessagingApiClient;
15-
16-
// ES6 modules or TypeScript
13+
// ES modules or TypeScript
1714
import { messagingApi } from '@line/bot-sdk';
1815
const { MessagingApiClient } = messagingApi;
16+
// OR
17+
import * as line from '@line/bot-sdk';
18+
const MessagingApiClient = line.messagingApi.MessagingApiClient;
19+
20+
// CommonJS
21+
const MessagingApiClient = require('@line/bot-sdk').messagingApi.MessagingApiClient;
1922
```
2023

2124
To create a client instance:

docs/guide/webhook.md

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -38,44 +38,30 @@ We skip the detailed guide for Express. If more information is needed about
3838
Express, please refer to its documentation.
3939

4040
Here is an example of an HTTP server built with Express.
41-
42-
``` js
43-
const express = require('express')
44-
45-
const app = express()
46-
47-
app.post('/webhook', (req, res) => {
48-
res.json({})
49-
})
50-
51-
app.listen(8080)
52-
```
53-
5441
The server above listens to 8080 and will response with an empty object for
5542
`POST /webhook`. We will add webhook functionality to this server.
5643

5744
``` js
58-
const express = require('express')
59-
const middleware = require('@line/bot-sdk').middleware
45+
import express from 'express'
46+
import { middleware } from '@line/bot-sdk'
6047

6148
const app = express()
6249

6350
const config = {
64-
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
6551
channelSecret: 'YOUR_CHANNEL_SECRET'
6652
}
6753

6854
app.post('/webhook', middleware(config), (req, res) => {
69-
req.body.events // webhook event objects
70-
req.body.destination // user ID of the bot (optional)
55+
req.body.events // webhook event objects from LINE Platform
56+
req.body.destination // user ID of the bot
7157
...
7258
})
7359

7460
app.listen(8080)
7561
```
7662

77-
We have imported `middleware` from the package and make the Express app to use
78-
the middleware. The middlware validates the request and parses webhook event
63+
We have imported `middleware` from `@line/bot-sdk` and make the Express app to use
64+
the middleware. The middleware validates the request and parses webhook event
7965
object. It embeds body-parser and parses them to objects. If you have a reason
8066
to use another body-parser separately for other routes, please keep in mind the
8167
followings.
@@ -131,15 +117,12 @@ For type references of the errors, please refer to [the API reference](../apidoc
131117
The errors can be handled with [error middleware](https://github.com/senchalabs/connect#error-middleware).
132118

133119
``` js
134-
const express = require('express')
135-
const middleware = require('@line/bot-sdk').middleware
136-
const JSONParseError = require('@line/bot-sdk').JSONParseError
137-
const SignatureValidationFailed = require('@line/bot-sdk').SignatureValidationFailed
120+
import express from 'express'
121+
import {middleware, JSONParseError, SignatureValidationFailed} from '@line/bot-sdk'
138122

139123
const app = express()
140124

141125
const config = {
142-
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
143126
channelSecret: 'YOUR_CHANNEL_SECRET'
144127
}
145128

@@ -163,6 +146,8 @@ app.use((err, req, res, next) => {
163146
app.listen(8080)
164147
```
165148

149+
You can read other examples in [lien-bot-sdk-nodejs/examples](https://github.com/line/line-bot-sdk-nodejs/tree/master/examples)
150+
166151
## HTTPS
167152

168153
The webhook URL should have HTTPS protocol. There are several ways to build an

examples/echo-bot-esm/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Echo Bot (ES Modules)
2+
3+
An example LINE bot just to echo messages written in ES modules.
4+
5+
## How to use
6+
7+
### Install deps
8+
9+
``` shell
10+
$ npm build-sdk
11+
$ npm install
12+
```
13+
14+
### Configuration
15+
16+
``` shell
17+
$ export CHANNEL_SECRET=YOUR_CHANNEL_SECRET
18+
$ export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN
19+
$ export PORT=1234
20+
```
21+
22+
### Run
23+
24+
``` shell
25+
$ node .
26+
```
27+
28+
## Webhook URL
29+
30+
```
31+
https://your.base.url/callback
32+
```

examples/echo-bot-esm/index.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import * as line from '@line/bot-sdk'
2+
import express from 'express'
3+
4+
// create LINE SDK config from env variables
5+
const config = {
6+
channelSecret: process.env.CHANNEL_SECRET,
7+
};
8+
9+
// create LINE SDK client
10+
const client = new line.messagingApi.MessagingApiClient({
11+
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN
12+
});
13+
14+
// create Express app
15+
// about Express itself: https://expressjs.com/
16+
const app = express();
17+
18+
// register a webhook handler with middleware
19+
// about the middleware, please refer to doc
20+
app.post('/callback', line.middleware(config), (req, res) => {
21+
Promise
22+
.all(req.body.events.map(handleEvent))
23+
.then((result) => res.json(result))
24+
.catch((err) => {
25+
console.error(err);
26+
res.status(500).end();
27+
});
28+
});
29+
30+
// event handler
31+
function handleEvent(event) {
32+
if (event.type !== 'message' || event.message.type !== 'text') {
33+
// ignore non-text-message event
34+
return Promise.resolve(null);
35+
}
36+
37+
// create an echoing text message
38+
const echo = { type: 'text', text: event.message.text };
39+
40+
// use reply API
41+
return client.replyMessage({
42+
replyToken: event.replyToken,
43+
messages: [echo],
44+
});
45+
}
46+
47+
// listen on port
48+
const port = process.env.PORT || 3000;
49+
app.listen(port, () => {
50+
console.log(`listening on ${port}`);
51+
});

0 commit comments

Comments
 (0)