Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update example and document for ESM #810

Merged
merged 6 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export default {
{ text: 'Guide', link: '/guide.html' },
{ text: 'API Reference', link: '/apidocs/modules.html' },
{ text: 'Contributing', link: '/CONTRIBUTING.html' },
{ text: 'LINE Developers', link: 'https://developers.line.biz/en/' },
{ text: 'GitHub', link: 'https://github.com/line/line-bot-sdk-nodejs/' },
],
// Sidebar items
Expand Down
55 changes: 36 additions & 19 deletions docs/getting-started/basic-usage.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# Basic Usage

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

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

``` js
// ES Modules or TypeScript
import * as line from '@line/bot-sdk';

// CommonJS
const line = require('@line/bot-sdk');

// ES2015 modules or TypeScript
import * as line from '@line/bot-sdk';
```

## Configuration
Expand All @@ -26,7 +26,6 @@ new line.messagingApi.MessagingApiClient({
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
});
line.middleware({
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
channelSecret: 'YOUR_CHANNEL_SECRET'
});
```
Expand All @@ -36,39 +35,57 @@ line.middleware({
Here is a synopsis of echoing webhook server with [Express](https://expressjs.com/):

``` js
const express = require('express');
const line = require('@line/bot-sdk');
import * as line from '@line/bot-sdk'
import express from 'express'

// create LINE SDK config from env variables
const config = {
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
channelSecret: 'YOUR_CHANNEL_SECRET'
channelSecret: process.env.CHANNEL_SECRET,
};

// create LINE SDK client
const client = new line.messagingApi.MessagingApiClient({
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN
});

// create Express app
// about Express itself: https://expressjs.com/
const app = express();
app.post('/webhook', line.middleware(config), (req, res) => {

// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/callback', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result));
.then((result) => res.json(result))
.catch((err) => {
console.error(err);
res.status(500).end();
});
});

const client = new line.messagingApi.MessagingApiClient({
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
});
// event handler
function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}

// create an echoing text message
const echo = { type: 'text', text: event.message.text };

// use reply API
return client.replyMessage({
replyToken: event.replyToken,
messages: [{
type: 'text',
text: event.message.text
}],
messages: [echo],
});
}

app.listen(3000);
// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});
```

The full examples with comments can be found
Expand Down
11 changes: 7 additions & 4 deletions docs/guide/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ For type signatures of the methods, please refer to [its API reference](../apido
The `MessagingApiClient` class is provided by the main module.

``` js
// CommonJS
const MessagingApiClient = require('@line/bot-sdk').messagingApi.MessagingApiClient;

// ES6 modules or TypeScript
// ES modules or TypeScript
import { messagingApi } from '@line/bot-sdk';
const { MessagingApiClient } = messagingApi;
// OR
import * as line from '@line/bot-sdk';
const MessagingApiClient = line.messagingApi.MessagingApiClient;

// CommonJS
const MessagingApiClient = require('@line/bot-sdk').messagingApi.MessagingApiClient;
```

To create a client instance:
Expand Down
35 changes: 10 additions & 25 deletions docs/guide/webhook.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,44 +38,30 @@ We skip the detailed guide for Express. If more information is needed about
Express, please refer to its documentation.

Here is an example of an HTTP server built with Express.

``` js
const express = require('express')

const app = express()

app.post('/webhook', (req, res) => {
res.json({})
})

app.listen(8080)
```

The server above listens to 8080 and will response with an empty object for
`POST /webhook`. We will add webhook functionality to this server.

``` js
const express = require('express')
const middleware = require('@line/bot-sdk').middleware
import express from 'express'
import { middleware } from '@line/bot-sdk'

const app = express()

const config = {
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
channelSecret: 'YOUR_CHANNEL_SECRET'
}

app.post('/webhook', middleware(config), (req, res) => {
req.body.events // webhook event objects
req.body.destination // user ID of the bot (optional)
req.body.events // webhook event objects from LINE Platform
req.body.destination // user ID of the bot
...
})

app.listen(8080)
```

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

``` js
const express = require('express')
const middleware = require('@line/bot-sdk').middleware
const JSONParseError = require('@line/bot-sdk').JSONParseError
const SignatureValidationFailed = require('@line/bot-sdk').SignatureValidationFailed
import express from 'express'
import {middleware, JSONParseError, SignatureValidationFailed} from '@line/bot-sdk'

const app = express()

const config = {
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN',
channelSecret: 'YOUR_CHANNEL_SECRET'
}

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

You can read other examples in [lien-bot-sdk-nodejs/examples](https://github.com/line/line-bot-sdk-nodejs/tree/master/examples)

## HTTPS

The webhook URL should have HTTPS protocol. There are several ways to build an
Expand Down
32 changes: 32 additions & 0 deletions examples/echo-bot-esm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Echo Bot (ES Modules)

An example LINE bot just to echo messages written in ES modules.

## How to use

### Install deps

``` shell
$ npm build-sdk
$ npm install
```

### Configuration

``` shell
$ export CHANNEL_SECRET=YOUR_CHANNEL_SECRET
$ export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN
$ export PORT=1234
```

### Run

``` shell
$ node .
```

## Webhook URL

```
https://your.base.url/callback
```
51 changes: 51 additions & 0 deletions examples/echo-bot-esm/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as line from '@line/bot-sdk'
import express from 'express'

// create LINE SDK config from env variables
const config = {
channelSecret: process.env.CHANNEL_SECRET,
};

// create LINE SDK client
const client = new line.messagingApi.MessagingApiClient({
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN
});

// create Express app
// about Express itself: https://expressjs.com/
const app = express();

// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post('/callback', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err) => {
console.error(err);
res.status(500).end();
});
});

// event handler
function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
// ignore non-text-message event
return Promise.resolve(null);
}

// create an echoing text message
const echo = { type: 'text', text: event.message.text };

// use reply API
return client.replyMessage({
replyToken: event.replyToken,
messages: [echo],
});
}

// listen on port
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});
Loading