├── .eslintrc.js
├── .github
└── workflows
│ ├── release.yml
│ └── test.yml
├── .gitignore
├── .releaserc
├── LICENSE
├── README.md
├── babel.config.js
├── jest.config.js
├── jest.setup.js
├── package.json
├── src
├── __mocks__
│ ├── @skolplattformen
│ │ └── embedded-api.js
│ ├── AsyncStorage.js
│ └── reporter.js
├── actions.ts
├── childlists.test.js
├── childlists.ts
├── context.test.js
├── context.ts
├── fake.test.js
├── hooks.ts
├── index.ts
├── logout.test.js
├── middleware.ts
├── provider.test.jsx
├── provider.tsx
├── reducers.ts
├── store.ts
├── types.ts
├── useCalendar.test.js
├── useChildList.test.js
├── useClassmates.test.js
├── useEtjanstChildren.test.js
├── useMenu.test.js
├── useNews.test.js
├── useNewsDetails.test.js
├── useNotifications.test.js
├── useSchedule.test.js
├── useSkola24Children.test.js
├── useTimetable.test.js
└── useUser.test.js
├── tsconfig.json
└── yarn.lock
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: [
3 | 'airbnb-typescript',
4 | 'plugin:jest/recommended'
5 | ],
6 | parserOptions: {
7 | project: `./tsconfig.json`,
8 | },
9 | rules: {
10 | '@typescript-eslint/semi': ['error', 'never'],
11 | 'jest/no-mocks-import': [0],
12 | 'max-len': [1, 110],
13 | 'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx', '.tsx'] }],
14 | },
15 | }
16 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 | on:
3 | push:
4 | branches:
5 | - main
6 | jobs:
7 | release:
8 | name: Release
9 | runs-on: ubuntu-18.04
10 | steps:
11 | - name: Checkout
12 | uses: actions/checkout@v2
13 | with:
14 | fetch-depth: 0
15 | - name: Setup Node.js
16 | uses: actions/setup-node@v1
17 | with:
18 | node-version: 14
19 | - name: Install dependencies
20 | run: yarn install --immutable --silent --non-interactive 2> >(grep -v warning 1>&2)
21 | - name: Build
22 | run: yarn build
23 | - name: Release
24 | env:
25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
26 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
27 | run: npx semantic-release
28 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # This workflow will do a clean install of node dependencies and run tests
2 |
3 | name: Test
4 |
5 | on:
6 | pull_request:
7 | branches: [main]
8 |
9 | jobs:
10 | unit:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Setup Node.js and run tests
15 | uses: actions/setup-node@v2.1.2
16 | with:
17 | node-version: 14.x
18 | - run: yarn install --immutable --silent --non-interactive 2> >(grep -v warning 1>&2)
19 | - run: yarn lint
20 | - run: yarn test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | record
107 |
--------------------------------------------------------------------------------
/.releaserc:
--------------------------------------------------------------------------------
1 | {
2 | "branches": ["main"]
3 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2021 Johan Öbrink
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # @skolplattformen/api-hooks
2 |
3 | 1. [Installing](#installing)
4 | 1. [Login / logout](#login--logout)
5 | 1. [Get data](#get-data)
6 | 1. [Fake mode](#fake-mode)
7 |
8 |
9 | ## Installing
10 |
11 | ```npm i -S @skolplattformen/api-hooks @skolplattformen/embedded-api```
12 |
13 | ```yarn add @skolplattformen/api-hooks @skolplattformen/embedded-api```
14 |
15 | ## ApiProvider
16 |
17 | In order to use api hooks, you must wrap your app in an ApiProvider
18 |
19 | ```javascript
20 | import React from 'react'
21 | import { ApiProvider } from '@skolplattformen/api-hooks'
22 | import init from '@skolplattformen/embedded-api'
23 | import { CookieManager } from '@react-native-community/cookies'
24 | import AsyncStorage from '@react-native-async-storage/async-storage'
25 | import { RootComponent } from './components/root'
26 | import crashlytics from '@react-native-firebase/crashlytics'
27 |
28 | const api = init(fetch, () => CookieManager.clearAll())
29 | const reporter = {
30 | log: (message) => crashlytics().log(message),
31 | error: (error, label) => crashlytics().recordError(error, label),
32 | }
33 |
34 | export default () => (
35 |
36 |
37 |
38 | )
39 | ```
40 |
41 | ## Login / logout
42 |
43 | ```javascript
44 | import { useApi } from '@skolplattformen/api-hooks'
45 |
46 | export default function LoginController () {
47 | const { api, isLoggedIn } = useApi()
48 |
49 | api.on('login', () => { /* do login stuff */ })
50 | api.on('logout', () => { /* do logout stuff */ })
51 |
52 | const [personalNumber, setPersonalNumber] = useState()
53 | const [bankIdStatus, setBankIdStatus] = useState('')
54 |
55 | const doLogin = async () => {
56 | const status = await api.login(personalNumber)
57 |
58 | openBankID(status.token)
59 |
60 | status.on('PENDING', () => { setBankIdStatus('BankID app not yet opened') })
61 | status.on('USER_SIGN', () => { setBankIdStatus('BankID app is open') })
62 | status.on('OK', () => { setBankIdStatus('BankID signed. NOTE! User is NOT yet logged in!') })
63 | status.on('ERROR', (err) => { setBankIdStatus('BankID failed') })
64 | })
65 |
66 | return (
67 |
68 |
69 |
73 | )
74 | }
75 | ```
76 |
77 | ## Get data
78 |
79 | 1. [General](#general)
80 | 1. [useCalendar](#usecalendar)
81 | 1. [useChildList](#usechildList)
82 | 1. [useClassmates](#useclassmates)
83 | 1. [useMenu](#usemenu)
84 | 1. [useNews](#usenews)
85 | 1. [useNotifications](#usenotifications)
86 | 1. [useSchedule](#useschedule)
87 | 1. [useUser](#useuser)
88 |
89 | ### General
90 |
91 | The data hooks return a `State` object exposing the following properties:
92 |
93 | | Property | Description |
94 | |----------|----------------------------------|
95 | | `status` | `pending` `loading` `loaded` |
96 | | `data` | The requested data |
97 | | `error` | Error from the API call if any |
98 | | `reload` | Function that triggers a reload |
99 |
100 | The hook will return a useable default for data at first (usually empty `[]`).
101 | It then checks the cache (`AsyncStorage`) for any value and, if exists, updates data.
102 | Simultaneously the API is called. This only automatically happens once during the
103 | lifetime of the app. If several instances of the same hook are used, the data will be
104 | shared and only one API call made.
105 | When `reload` is called, a new API call will be made and all hook instances will have
106 | their `status`, `data` and `error` updated.
107 |
108 | ### useCalendar
109 |
110 | ```javascript
111 | import { useCalendar } from '@skolplattformen/api-hooks'
112 |
113 | export default function CalendarComponent ({ selectedChild }) => {
114 | const { status, data, error, reload } = useCalendar(selectedChild)
115 |
116 | return (
117 |
118 | { status === 'loading' && }
119 | { error && { error.message }}
120 | { data.map((item) => (
121 |
122 | ))}
123 | { status !== 'loading' && status !== 'pending' &&
125 | )
126 | }
127 | ```
128 |
129 | ### useChildList
130 |
131 | ```javascript
132 | import { useChildList } from '@skolplattformen/api-hooks'
133 |
134 | export default function ChildListComponent () => {
135 | const { status, data, error, reload } = useChildList()
136 |
137 | return (
138 |
139 | { status === 'loading' && }
140 | { error && { error.message }}
141 | { data.map((child) => (
142 | {child.firstName} {child.lastName}
143 | ))}
144 | { status !== 'loading' && status !== 'pending' &&
146 | )
147 | }
148 | ```
149 |
150 | ### useClassmates
151 |
152 | ```javascript
153 | import { useClassmates } from '@skolplattformen/api-hooks'
154 |
155 | export default function ClassmatesComponent ({ selectedChild }) => {
156 | const { status, data, error, reload } = useClassmates(selectedChild)
157 |
158 | return (
159 |
160 | { status === 'loading' && }
161 | { error && { error.message }}
162 | { data.map((classmate) => (
163 |
164 | ))}
165 | { status !== 'loading' && status !== 'pending' &&
167 | )
168 | }
169 | ```
170 |
171 | ### useMenu
172 |
173 | ```javascript
174 | import { useMenu } from '@skolplattformen/api-hooks'
175 |
176 | export default function MenuComponent ({ selectedChild }) => {
177 | const { status, data, error, reload } = useMenu(selectedChild)
178 |
179 | return (
180 |
181 | { status === 'loading' && }
182 | { error && { error.message }}
183 | { data.map((item) => (
184 |
185 | ))}
186 | { status !== 'loading' && status !== 'pending' &&
188 | )
189 | }
190 | ```
191 |
192 | ### useNews
193 |
194 | ```javascript
195 | import { useNews } from '@skolplattformen/api-hooks'
196 |
197 | export default function NewsComponent ({ selectedChild }) => {
198 | const { status, data, error, reload } = useNews(selectedChild)
199 |
200 | return (
201 |
202 | { status === 'loading' && }
203 | { error && { error.message }}
204 | { data.map((item) => (
205 |
206 | ))}
207 | { status !== 'loading' && status !== 'pending' &&
209 | )
210 | }
211 | ```
212 |
213 | To display image from `NewsItem`:
214 |
215 | ```javascript
216 | import { useApi } from '@skolplattformen/api-hooks'
217 |
218 | export default function NewsItem ({ item }) => {
219 | const { api } = useApi()
220 | const cookie = api.getSessionCookie()
221 |
222 | return (
223 |
224 | { cookie &&
225 | }
226 |
227 | )
228 | }
229 | ```
230 |
231 | ### useNotifications
232 |
233 | ```javascript
234 | import { useNotifications } from '@skolplattformen/api-hooks'
235 |
236 | export default function NotificationsComponent ({ selectedChild }) => {
237 | const { status, data, error, reload } = useNotifications(selectedChild)
238 |
239 | return (
240 |
241 | { status === 'loading' && }
242 | { error && { error.message }}
243 | { data.map((item) => (
244 |
245 | ))}
246 | { status !== 'loading' && status !== 'pending' &&
248 | )
249 | }
250 | ```
251 |
252 | To show content of `NotificationItem` url:
253 |
254 | ```javascript
255 | import { useApi } from '@skolplattformen/api-hooks'
256 | import { WebView } from 'react-native-webview'
257 |
258 | export default function Notification ({ item }) => {
259 | const { cookie } = useApi()
260 |
261 | return (
262 |
263 |
264 |
265 | )
266 | }
267 | ```
268 |
269 | ### useSchedule
270 |
271 | ```javascript
272 | import { DateTime } from 'luxon'
273 | import { useSchedule } from '@skolplattformen/api-hooks'
274 |
275 | export default function ScheduleComponent ({ selectedChild }) => {
276 | const from = DateTime.local()
277 | const to = DateTime.local.plus({ week: 1 })
278 | const { status, data, error, reload } = useSchedule(selectedChild, from, to)
279 |
280 | return (
281 |
282 | { status === 'loading' && }
283 | { error && { error.message }}
284 | { data.map((item) => (
285 |
286 | ))}
287 | { status !== 'loading' && status !== 'pending' &&
289 | )
290 | }
291 | ```
292 |
293 | ### useUser
294 |
295 | ```javascript
296 | import { useUser } from '@skolplattformen/api-hooks'
297 |
298 | export default function UserComponent () => {
299 | const { status, data, error, reload } = useUser()
300 |
301 | return (
302 |
303 | { status === 'loading' && }
304 | { error && { error.message }}
305 | { data &&
306 | <>
307 | {data.firstName} {data.lastName}
308 | {data.email}
309 | >
310 | }
311 | { status !== 'loading' && status !== 'pending' &&
313 | )
314 | }
315 | ```
316 |
317 | ## Fake mode
318 |
319 | To make testing easier, fake mode can be enabled at login. Just use any of the magic
320 | personal numbers: `12121212121212`, `201212121212` or `1212121212`.
321 | The returned login status will have `token` set to `'fake'`.
322 |
323 | ```javascript
324 | import { useApi } from '@skolplattformen/api-hooks'
325 |
326 |
327 | import { useApi } from '@skolplattformen/api-hooks'
328 |
329 | export default function LoginController () {
330 | const { api, isLoggedIn } = useApi()
331 |
332 | const [personalNumber, setPersonalNumber] = useState()
333 | const [bankIdStatus, setBankIdStatus] = useState('')
334 |
335 | api.on('login', () => { /* do login stuff */ })
336 | api.on('logout', () => { /* do logout stuff */ })
337 |
338 | const doLogin = async () => {
339 | const status = await api.login(personalNumber)
340 |
341 | if (status.token !== 'fake') {
342 | openBankID(status.token)
343 | } else {
344 | // Login will succeed
345 | // All data will be faked
346 | // No server calls will be made
347 | }
348 | })
349 |
350 | return (
351 |
352 |
353 |
357 | )
358 | }
359 | ```
360 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | '@babel/preset-env',
4 | '@babel/preset-react',
5 | '@babel/preset-typescript',
6 | ],
7 | }
8 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | // Automatically clear mock calls and instances between every test
3 | clearMocks: true,
4 | // The directory where Jest should output its coverage files
5 | coverageDirectory: 'coverage',
6 | // Indicates which provider should be used to instrument code for coverage
7 | coverageProvider: 'v8',
8 | // The paths to modules that run some code to configure or set up the testing environment before each test
9 | // setupFiles: ['/jest.setup.js'],
10 | // The test environment that will be used for testing
11 | testEnvironment: 'jsdom',
12 | setupFilesAfterEnv: ['/jest.setup.js'],
13 | }
14 |
--------------------------------------------------------------------------------
/jest.setup.js:
--------------------------------------------------------------------------------
1 | import 'regenerator-runtime/runtime'
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@skolplattformen/api-hooks",
3 | "description": "React hooks for accessing api with cached results",
4 | "version": "0.0.1",
5 | "main": "dist/index.js",
6 | "types": "dist/index.d.ts",
7 | "files": [
8 | "dist/**/*"
9 | ],
10 | "repository": "git@github.com:kolplattformen/api-hooks.git",
11 | "author": "Johan Öbrink ",
12 | "license": "Apache-2.0",
13 | "private": false,
14 | "scripts": {
15 | "lint": "eslint 'src/**/*.ts' --quiet --fix",
16 | "test": "jest",
17 | "build": "tsc",
18 | "prepare": "yarn build",
19 | "publish-package": "npm publish --access public"
20 | },
21 | "dependencies": {
22 | "luxon": "^1.26.0",
23 | "react-redux": "^7.2.3",
24 | "redux": "^4.0.5"
25 | },
26 | "peerDependencies": {
27 | "@skolplattformen/curriculum": "^1.3.0",
28 | "@skolplattformen/embedded-api": "^5.1.0",
29 | "react": "^16.11.0"
30 | },
31 | "devDependencies": {
32 | "@babel/preset-env": "^7.13.15",
33 | "@babel/preset-react": "^7.13.13",
34 | "@babel/preset-typescript": "^7.13.0",
35 | "@skolplattformen/curriculum": "^1.3.0",
36 | "@skolplattformen/embedded-api": "^5.1.0",
37 | "@testing-library/jest-dom": "^5.11.10",
38 | "@testing-library/react": "^11.2.6",
39 | "@testing-library/react-hooks": "^5.1.1",
40 | "@types/jest": "^26.0.22",
41 | "@types/luxon": "^1.26.4",
42 | "@types/react": "^16.14.3",
43 | "@types/react-redux": "^7.1.16",
44 | "@typescript-eslint/eslint-plugin": "^4.21.0",
45 | "babel-jest": "^26.6.3",
46 | "eslint": "^7.23.0",
47 | "eslint-config-airbnb-typescript": "^12.3.1",
48 | "eslint-plugin-import": "^2.22.1",
49 | "eslint-plugin-jest": "^24.3.4",
50 | "eslint-plugin-jsx-a11y": "^6.4.1",
51 | "eslint-plugin-react": "^7.23.2",
52 | "eslint-plugin-react-hooks": "^4.2.0",
53 | "events": "^3.3.0",
54 | "jest": "^26.6.3",
55 | "react": "^16.11.0",
56 | "react-dom": "^16.11.0",
57 | "react-test-renderer": "^16.11.0",
58 | "regenerator-runtime": "^0.13.7",
59 | "typescript": "^3.9.7"
60 | },
61 | "publishConfig": {
62 | "access": "public"
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/__mocks__/@skolplattformen/embedded-api.js:
--------------------------------------------------------------------------------
1 | import { EventEmitter } from 'events'
2 |
3 | const emitter = new EventEmitter()
4 |
5 | const createApi = () => ({
6 | emitter,
7 | isLoggedIn: false,
8 | login: jest.fn(),
9 | logout: jest.fn(),
10 | on: jest.fn().mockImplementation((...args) => emitter.on(...args)),
11 | off: jest.fn().mockImplementation((...args) => emitter.off(...args)),
12 |
13 | getSession: jest.fn(),
14 | getPersonalNumber: jest.fn(),
15 |
16 | getCalendar: jest.fn(),
17 | getChildren: jest.fn(),
18 | getSkola24Children: jest.fn(),
19 | getClassmates: jest.fn(),
20 | getMenu: jest.fn(),
21 | getNews: jest.fn(),
22 | getNewsDetails: jest.fn(),
23 | getNotifications: jest.fn(),
24 | getSchedule: jest.fn(),
25 | getTimetable: jest.fn(),
26 | getUser: jest.fn(),
27 | })
28 | const init = jest.fn().mockImplementation(() => createApi())
29 |
30 | export default init
31 |
--------------------------------------------------------------------------------
/src/__mocks__/AsyncStorage.js:
--------------------------------------------------------------------------------
1 | const pause = (ms = 0) => new Promise((r) => setTimeout(r, ms))
2 |
3 | export default (init = {}, delay = 0) => {
4 | const cache = {}
5 | Object.keys(init).forEach((key) => {
6 | cache[key] = JSON.stringify(init[key])
7 | })
8 | const getItem = async (key) => {
9 | await pause(delay)
10 | return cache[key] || null
11 | }
12 | const setItem = async (key, val) => {
13 | await pause(delay)
14 | cache[key] = val
15 | }
16 | const clear = () => {
17 | Object.keys(cache).forEach((key) => { cache[key] = undefined })
18 | }
19 | return {
20 | getItem, setItem, cache, clear,
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/__mocks__/reporter.js:
--------------------------------------------------------------------------------
1 | const reporter = {
2 | log: jest.fn().mockName('log'),
3 | error: jest.fn().mockName('error'),
4 | }
5 |
6 | export default reporter
7 |
--------------------------------------------------------------------------------
/src/actions.ts:
--------------------------------------------------------------------------------
1 | import {
2 | EntityAction, EntityName, ExtraActionProps,
3 | } from './types'
4 |
5 | // eslint-disable-next-line import/prefer-default-export
6 | export const loadAction = (entity: EntityName, extra: ExtraActionProps): EntityAction => ({
7 | entity,
8 | extra,
9 | type: 'GET_FROM_API',
10 | })
11 |
--------------------------------------------------------------------------------
/src/childlists.test.js:
--------------------------------------------------------------------------------
1 | import { merge } from './childlists'
2 |
3 | describe('childlists', () => {
4 | describe('merge', () => {
5 | it('works with empty skola24children list', () => {
6 | const etjanstChildren = [
7 | { name: 'Uwe Übrink (elev)' },
8 | { name: 'Cassius Übrink (elev)' },
9 | ]
10 | const skola24Children = []
11 |
12 | const children = [
13 | { name: 'Uwe Übrink (elev)' },
14 | { name: 'Cassius Übrink (elev)' },
15 | ]
16 | expect(merge(etjanstChildren, skola24Children)).toEqual(children)
17 | })
18 | it('works with same length skola24children list', () => {
19 | const etjanstChildren = [
20 | { name: 'Uwe Übrink (elev)' },
21 | { name: 'Cassius Übrink (elev)' },
22 | ]
23 | const skola24Children = [
24 | { firstName: 'Uwe', lastName: 'Vredstein Übrink' },
25 | { firstName: 'Cassius', lastName: 'Vredstein Übrink' },
26 | ]
27 |
28 | const children = [
29 | { name: 'Uwe Übrink (elev)', firstName: 'Uwe', lastName: 'Vredstein Übrink' },
30 | { name: 'Cassius Übrink (elev)', firstName: 'Cassius', lastName: 'Vredstein Übrink' },
31 | ]
32 | expect(merge(etjanstChildren, skola24Children)).toEqual(children)
33 | })
34 | it('works with different length skola24children list', () => {
35 | const etjanstChildren = [
36 | { name: 'Uwe Übrink (elev)' },
37 | { name: 'Cassius Übrink (elev)' },
38 | ]
39 | const skola24Children = [
40 | { firstName: 'Uwe', lastName: 'Vredstein Übrink' },
41 | ]
42 |
43 | const children = [
44 | { name: 'Uwe Übrink (elev)', firstName: 'Uwe', lastName: 'Vredstein Übrink' },
45 | { name: 'Cassius Übrink (elev)' },
46 | ]
47 | expect(merge(etjanstChildren, skola24Children)).toEqual(children)
48 | })
49 | it('works with non matching skola24children list', () => {
50 | const etjanstChildren = [
51 | { name: 'Uwe Übrink (elev)' },
52 | { name: 'Cassius Übrink (elev)' },
53 | ]
54 | const skola24Children = [
55 | { firstName: 'Uwe', lastName: 'Vredstein Übrink' },
56 | { firstName: 'Rolph', lastName: 'Gögendorff Bröök' },
57 | ]
58 |
59 | const children = [
60 | { name: 'Uwe Übrink (elev)', firstName: 'Uwe', lastName: 'Vredstein Übrink' },
61 | { name: 'Cassius Übrink (elev)' },
62 | ]
63 | expect(merge(etjanstChildren, skola24Children)).toEqual(children)
64 | })
65 | })
66 | })
67 |
--------------------------------------------------------------------------------
/src/childlists.ts:
--------------------------------------------------------------------------------
1 | import { Child, EtjanstChild, Skola24Child } from '@skolplattformen/embedded-api'
2 |
3 | // eslint-disable-next-line import/prefer-default-export
4 | export const merge = (etjanstChildren: EtjanstChild[], skola24Children: Skola24Child[]): Child[] => (
5 | etjanstChildren.map((etjanstChild) => {
6 | const skola24Child: Skola24Child = (
7 | skola24Children.find((s24c) => s24c.firstName && etjanstChild.name.startsWith(s24c.firstName)) || {}
8 | )
9 | const child: Child = {
10 | ...etjanstChild,
11 | ...skola24Child,
12 | }
13 | return child
14 | })
15 | )
16 |
--------------------------------------------------------------------------------
/src/context.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { act, renderHook } from '@testing-library/react-hooks'
3 | import { ApiProvider } from './provider'
4 | import init from './__mocks__/@skolplattformen/embedded-api'
5 | import { useApi } from './context'
6 |
7 | describe('useApi()', () => {
8 | let api
9 | beforeEach(() => {
10 | api = init()
11 | })
12 | const wrapper = ({ children }) => (
13 | {children}
14 | )
15 | it('exposes api', () => {
16 | const { result } = renderHook(() => useApi(), { wrapper })
17 |
18 | expect(result.current.api).toBeTruthy()
19 | })
20 | it('exposes isLoggedIn', () => {
21 | const { result } = renderHook(() => useApi(), { wrapper })
22 |
23 | expect(result.current.isLoggedIn).toBe(false)
24 | })
25 | it('updates isLoggedIn', async () => {
26 | const { result, waitForValueToChange } = renderHook(() => useApi(), { wrapper })
27 | await act(async () => {
28 | api.isLoggedIn = true
29 | api.emitter.emit('login')
30 | await waitForValueToChange(() => result.current.isLoggedIn)
31 | })
32 |
33 | expect(result.current.isLoggedIn).toBe(true)
34 | })
35 | it('updates isFake', async () => {
36 | const { result, waitForValueToChange } = renderHook(() => useApi(), { wrapper })
37 | await act(async () => {
38 | api.isFake = true
39 | api.emitter.emit('login')
40 | await waitForValueToChange(() => result.current.isFake)
41 | })
42 |
43 | expect(result.current.isFake).toBe(true)
44 | })
45 | })
46 |
--------------------------------------------------------------------------------
/src/context.ts:
--------------------------------------------------------------------------------
1 | import { createContext, useContext } from 'react'
2 | import { IApiContext } from './types'
3 |
4 | export const ApiContext = createContext({} as IApiContext)
5 |
6 | export const useApi = () => useContext(ApiContext)
7 |
--------------------------------------------------------------------------------
/src/fake.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { act, renderHook } from '@testing-library/react-hooks'
3 | import { ApiProvider } from '.'
4 | import createStorage from './__mocks__/AsyncStorage'
5 | import {
6 | useCalendar,
7 | useEtjanstChildren,
8 | useClassmates,
9 | useMenu,
10 | useNews,
11 | useNotifications,
12 | useSchedule,
13 | useUser,
14 | } from './hooks'
15 | import store from './store'
16 |
17 | const { default: init } = jest.requireActual('@skolplattformen/embedded-api')
18 |
19 | const wait = (ms) => new Promise((res) => setTimeout(res, ms))
20 |
21 | describe('hooks with fake data', () => {
22 | let api
23 | let storage
24 | const wrapper = ({ children }) => (
25 | {children}
26 | )
27 | beforeEach(async () => {
28 | api = init(() => { }, () => { })
29 | await api.login('121212121212')
30 |
31 | storage = createStorage({})
32 | })
33 | it('does not use cache', async () => {
34 | storage.cache.user = JSON.stringify({ user: 'cached' })
35 | await act(async () => {
36 | const {
37 | result,
38 | waitForNextUpdate,
39 | } = renderHook(() => useUser(), { wrapper })
40 |
41 | await waitForNextUpdate()
42 | await waitForNextUpdate()
43 | await waitForNextUpdate()
44 |
45 | expect(result.current.data).toEqual({
46 | firstName: 'Namn',
47 | lastName: 'Namnsson',
48 | isAuthenticated: true,
49 | })
50 | })
51 | })
52 | it('returns user', async () => {
53 | await act(async () => {
54 | const {
55 | result,
56 | waitForNextUpdate,
57 | } = renderHook(() => useUser(), { wrapper })
58 |
59 | await waitForNextUpdate()
60 | await waitForNextUpdate()
61 |
62 | expect(result.current.data).toEqual({
63 | firstName: 'Namn',
64 | lastName: 'Namnsson',
65 | isAuthenticated: true,
66 | })
67 | })
68 | })
69 | it('returns child list', async () => {
70 | await act(async () => {
71 | const {
72 | result,
73 | waitForNextUpdate,
74 | } = renderHook(() => useEtjanstChildren(), { wrapper })
75 |
76 | await waitForNextUpdate()
77 | await waitForNextUpdate()
78 | await waitForNextUpdate()
79 |
80 | expect(result.current.data).toHaveLength(2)
81 | })
82 | })
83 | describe('data belonging to one child', () => {
84 | let child
85 | beforeEach(async () => {
86 | [child] = await api.getChildren()
87 | })
88 | it('returns calendar', async () => {
89 | await act(async () => {
90 | const {
91 | result,
92 | waitForNextUpdate,
93 | } = renderHook(() => useCalendar(child), { wrapper })
94 |
95 | await waitForNextUpdate()
96 | await waitForNextUpdate()
97 |
98 | expect(result.current.data.length).toBeGreaterThan(1)
99 | })
100 | })
101 | it('returns classmates', async () => {
102 | await act(async () => {
103 | const {
104 | result,
105 | waitForNextUpdate,
106 | } = renderHook(() => useClassmates(child), { wrapper })
107 |
108 | await waitForNextUpdate()
109 | await waitForNextUpdate()
110 |
111 | expect(result.current.data.length).toBeGreaterThan(1)
112 | })
113 | })
114 | it('returns menu', async () => {
115 | await act(async () => {
116 | const {
117 | result,
118 | waitForNextUpdate,
119 | } = renderHook(() => useMenu(child), { wrapper })
120 |
121 | await waitForNextUpdate()
122 | await waitForNextUpdate()
123 |
124 | expect(result.current.data.length).toBeGreaterThan(1)
125 | })
126 | })
127 | it('returns news', async () => {
128 | await act(async () => {
129 | const {
130 | result,
131 | waitForNextUpdate,
132 | } = renderHook(() => useNews(child), { wrapper })
133 |
134 | await waitForNextUpdate()
135 | await waitForNextUpdate()
136 |
137 | expect(result.current.data.length).toBeGreaterThan(1)
138 | })
139 | })
140 | it('returns notifications', async () => {
141 | await act(async () => {
142 | const {
143 | result,
144 | waitForNextUpdate,
145 | } = renderHook(() => useNotifications(child), { wrapper })
146 |
147 | await waitForNextUpdate()
148 | await waitForNextUpdate()
149 |
150 | expect(result.current.data.length).toBeGreaterThan(1)
151 | })
152 | })
153 | it('returns schedule', async () => {
154 | const from = '2021-01-01'
155 | const to = '2021-01-08'
156 | await act(async () => {
157 | const {
158 | result,
159 | waitForNextUpdate,
160 | } = renderHook(() => useSchedule(child, from, to), { wrapper })
161 |
162 | await waitForNextUpdate()
163 | await waitForNextUpdate()
164 |
165 | // No fake schedule in embedded-api yet
166 | expect(result.current.data.length).not.toBeGreaterThan(1)
167 | })
168 | })
169 | })
170 | it('handles reloads', async () => {
171 | await act(async () => {
172 | store.dispatch({ type: 'CLEAR' })
173 |
174 | const [child] = await api.getChildren()
175 |
176 | const {
177 | result,
178 | waitForNextUpdate,
179 | } = renderHook(() => useNotifications(child), { wrapper })
180 |
181 | await waitForNextUpdate()
182 | expect(result.current.status).toEqual('loaded')
183 |
184 | result.current.reload()
185 | await wait(30)
186 |
187 | expect(result.current.status).toEqual('loaded')
188 | })
189 | })
190 | })
191 |
--------------------------------------------------------------------------------
/src/hooks.ts:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from 'react'
2 | import { useDispatch } from 'react-redux'
3 | import {
4 | Api,
5 | CalendarItem,
6 | Child,
7 | Classmate,
8 | EtjanstChild,
9 | MenuItem,
10 | NewsItem,
11 | Notification,
12 | ScheduleItem,
13 | Skola24Child,
14 | TimetableEntry,
15 | User,
16 | } from '@skolplattformen/embedded-api'
17 | import { DateTime } from 'luxon'
18 | import { Language } from '@skolplattformen/curriculum/dist/translations'
19 | import {
20 | ApiCall,
21 | EntityHookResult,
22 | EntityMap,
23 | EntityName,
24 | EntityStoreRootState,
25 | ExtraActionProps,
26 | } from './types'
27 | import { useApi } from './context'
28 | import { loadAction } from './actions'
29 | import store from './store'
30 | import { merge } from './childlists'
31 |
32 | interface StoreSelector {
33 | (state: EntityStoreRootState): EntityMap
34 | }
35 |
36 | const hook = (
37 | entityName: EntityName,
38 | key: string,
39 | defaultValue: T,
40 | selector: StoreSelector,
41 | apiCaller: (api: Api) => ApiCall,
42 | ): EntityHookResult => {
43 | const {
44 | api, isLoggedIn, reporter, storage,
45 | } = useApi()
46 |
47 | const getState = (): EntityStoreRootState => store.getState() as unknown as EntityStoreRootState
48 | const select = (storeState: EntityStoreRootState) => {
49 | const stateMap = selector(storeState) || {}
50 | const state = stateMap[key] || { status: 'pending', data: defaultValue }
51 | return state
52 | }
53 | const initialState = select(getState())
54 | const [state, setState] = useState(initialState)
55 | const dispatch = useDispatch()
56 |
57 | const load = (force = false) => {
58 | if (isLoggedIn && state.status !== 'loading' && ((force && !api.isFake) || state.status === 'pending')) {
59 | const extra: ExtraActionProps = {
60 | key,
61 | defaultValue,
62 | apiCall: apiCaller(api),
63 | retries: 0,
64 | }
65 |
66 | // Only use cache when not in fake mode
67 | if (!api.isFake) {
68 | const pnr = api.getPersonalNumber()
69 |
70 | // Only get from cache first time
71 | if (state.status === 'pending') {
72 | extra.getFromCache = () => storage.getItem(`${pnr}_${key}`)
73 | }
74 | extra.saveToCache = (value: string) => storage.setItem(`${pnr}_${key}`, value)
75 | }
76 | const action = loadAction(entityName, extra)
77 | dispatch(action)
78 | }
79 | }
80 | useEffect(() => { load() }, [isLoggedIn])
81 |
82 | let mounted: boolean
83 | useEffect(() => {
84 | mounted = true
85 | return () => { mounted = false }
86 | }, [])
87 |
88 | const listener = () => {
89 | if (!mounted) return
90 |
91 | const newState = select(getState())
92 | if (newState.status !== state.status
93 | || newState.data !== state.data
94 | || newState.error !== state.error) {
95 | setState(newState)
96 |
97 | if (newState.error) {
98 | const description = `Error getting ${entityName} from API`
99 | reporter.error(newState.error, description)
100 | }
101 | }
102 | }
103 | useEffect(() => store.subscribe(listener), [])
104 |
105 | return {
106 | ...state,
107 | reload: () => load(true),
108 | }
109 | }
110 |
111 | export const useEtjanstChildren = () => hook(
112 | 'ETJANST_CHILDREN',
113 | 'etjanst_children',
114 | [],
115 | (s) => s.etjanstChildren,
116 | (api) => () => api.getChildren(),
117 | )
118 |
119 | export const useSkola24Children = () => hook(
120 | 'SKOLA24_CHILDREN',
121 | 'skola24_children',
122 | [],
123 | (s) => s.skola24Children,
124 | (api) => () => api.getSkola24Children(),
125 | )
126 |
127 | export const useCalendar = (child: Child) => hook(
128 | 'CALENDAR',
129 | `calendar_${child.id}`,
130 | [],
131 | (s) => s.calendar,
132 | (api) => () => api.getCalendar(child),
133 | )
134 |
135 | export const useClassmates = (child: Child) => hook(
136 | 'CLASSMATES',
137 | `classmates_${child.id}`,
138 | [],
139 | (s) => s.classmates,
140 | (api) => () => api.getClassmates(child),
141 | )
142 |
143 | export const useMenu = (child: Child) => hook