adapt "writing a profile" guide to ctx-based parse fns 📝

[ci skip]
This commit is contained in:
Jannis R 2019-12-27 21:22:01 +01:00
parent 39a626784b
commit 4d11f34e1d
No known key found for this signature in database
GPG key ID: 0FE83946296A88A5

View file

@ -35,25 +35,33 @@ Assuming their HAFAS endpoint returns all line names prefixed with `foo `, we ca
```js ```js
// get the default line parser // get the default line parser
const createParseLine = require('hafas-client/parse/line') const parseLine = require('hafas-client/parse/line')
const createParseLineWithoutFoo = (profile, opt, data) => { // wrapper function with additional logic
const parseLine = createParseLine(profile, opt, data) const parseLineWithoutFoo = (ctx, rawLine) => {
const line = parseLine(ctx, rawLine)
// wrapper function with additional logic line.name = line.name.replace(/foo /g, '')
const parseLineWithoutFoo = (l) => { return line
const line = parseLine(l)
line.name = line.name.replace(/foo /g, '')
return line
}
return parseLineWithoutFoo
} }
profile.parseLine = createParseLineWithoutFoo myProfile.parseLine = parseLineWithoutFoo
``` ```
If you pass this profile into `hafas-client`, the `parseLine` method will override [the default one](../parse/line.js). If you pass this profile into `hafas-client`, the `parseLine` method will override [the default one](../parse/line.js).
You can also use the `parseHook` helper to reduce boilerplate:
```js
const {parseHook} = require('hafas-client/lib/profile-hooks')
const removeFoo = (ctx, rawLine) => ({
...ctx.parsed,
name: line.name.replace(/foo /g, '')
})
myProfile.parseLine = parseHook(parseLine, removeFoo)
```
## 1. Setup ## 1. Setup
*Note*: There are many ways to find the required values. This way is rather easy and has worked for most of the apps that we've looked at so far. *Note*: There are many ways to find the required values. This way is rather easy and has worked for most of the apps that we've looked at so far.