Skip to content

Commit 9e6b7f9

Browse files
committed
[add] Documentation for plugins
1 parent e1d9c34 commit 9e6b7f9

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

docs/plugins.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Plugins
2+
3+
1. [Overview](#overview)
4+
2. [Making a plugin](#making-a-plugin)
5+
3. [Handling failure](#handling-failure)
6+
7+
## Overview
8+
9+
Plugins provide a way to extend an application. They attempt to solve
10+
the problem of providing environment specific behavior. For example,
11+
when rendering on the server you often want to fetch data ahead of
12+
time, while in the browser you may need to establish a connection to
13+
websocket events or extract data from local storage.
14+
15+
## Making a plugin
16+
17+
Plugins are inspired by the API provided by HapiJS. This is no
18+
coincidence. Future version of Microcosm will aspire for greater
19+
adherence to the Hapi API to help share code and provide consistency.
20+
21+
At the moment, the only requirement is that plugins implement a
22+
`register` method:
23+
24+
```javascript
25+
let LazyPlugin = {
26+
register(app, options, next) {
27+
setTimeout(next, 2000);
28+
}
29+
}
30+
```
31+
32+
This plugin will delay execution of the app for 2 seconds. This
33+
expresses the nature of plugins. They can be asynchronous, to support
34+
non-immediate (but vital) tasks:
35+
36+
For example: What if you want to fetch data before an application begins?
37+
38+
```javascript
39+
import Route from 'stores/route'
40+
41+
let Prefetcher = {
42+
43+
register(app, options, next) {
44+
let route = app.get(Route)
45+
46+
route.fetchData()
47+
.then(app.seed)
48+
.then(i => next)
49+
}
50+
51+
}
52+
```
53+
54+
## Handling failure
55+
56+
Plugins can fail, for example what if fetching data returns a 500? The
57+
`next` function accepts an `error` argument:
58+
59+
```javascript
60+
import Route from 'stores/route'
61+
62+
let Prefetcher = {
63+
64+
register(app, options, next) {
65+
let route = app.get(Route)
66+
67+
route.fetchData()
68+
.then(app.seed)
69+
.then(i => next)
70+
.catch(error => next(error))
71+
}
72+
73+
}
74+
```
75+
76+
This will throw an error (and it will not be caught). You can handle
77+
this however you wish.

0 commit comments

Comments
 (0)