Skip to content

Patch Deploy #21

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

Merged
merged 17 commits into from
Jan 30, 2020
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
4 changes: 4 additions & 0 deletions .markdownlintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"MD036": false,
"MD001": false
}
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ cache:
branches:
only:
- master
- develop
notifications:
email: false
node_js:
Expand Down
208 changes: 44 additions & 164 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
# vue-router-middleware-plugin
# Vue Router Middleware Plugin

A vue.js plugin to implement a middleware pipeline for vue-router.
A vue-router middleware pipeline.

[![npm version](https://badge.fury.io/js/vue-router-middleware-plugin.svg)](https://badge.fury.io/js/vue-router-middleware-plugin)
[![Build Status](https://travis-ci.org/dsfx3d/vue-router-middleware-plugin.svg?branch=master)](https://travis-ci.org/dsfx3d/vue-router-middleware-plugin)
[![code cove](https://codecov.io/gh/dsfx3d/vue-router-middleware-plugin/branch/master/graph/badge.svg)](https://codecov.io/gh/dsfx3d/vue-router-middleware-plugin/branch/master/graph/badge.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/d1ab723bcfaa460aa9d12ccc7a54bf65)](https://www.codacy.com/manual/dsfx3d/vue-router-middleware-plugin?utm_source=github.com&utm_medium=referral&utm_content=dsfx3d/vue-router-middleware-plugin&utm_campaign=Badge_Grade)
![vue-router-middleware-plugin](https://badgen.net/bundlephobia/minzip/vue-router-middleware-plugin)

It can have many use cases like protecting a route or to request an API to populate the store before a route is loaded.
The plugin utilizes [vue-router navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards.html) to implement easy to use, readable and more organized middlewares for your routes.

> **Please Note:** Due to the very limited scope of this module, I do not anticipate need to making many changes to it. Expect long stretches of zero updates—that does not mean that the module is outdated.
The plugin utilizes [vue-router navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards.html)
to implement easy to use, readable and more organized middlewares for your routes.

## Installation

Expand All @@ -27,187 +25,69 @@ Install using Yarn
yarn add vue-router-middleware-plugin
```

## Usage

Create a middleware, `auth.js`

```javascript
import store from '~/store'

export default ({ to, from, redirect }) => {
if (!store.getters.isLoggedIn) {
redirect('/login')
// or
redirect(from)
// or
redirect(false)
}
}
```

> **Note:** Properties `to` and `from` are the same as in a vue router navigation gaurds. In __v2.0.0__ functin `next` has been replaced by `redirect` which can be called to redirect to a route. Now, there's no need to call `next` in each middleware to resolve it.
## Get Started in 3 Easy Steps

Register the plugin in your application.
1. Register middleware plugin in your app.

```javascript
import Vue from 'vue'
import MiddlewarePlugin from 'vue-router-middleware-plugin'
import router from '~/router'
import AuthMiddleware from '~router/middlewares/auth'
import LoggerMiddleware from '~router/middlewares/logger'

Vue.use(MiddlewarePlugin, router)

// register a globabl middleware
Vue.use(MiddlewarePlugin, { router, middleware: AuthMiddleware })

// register multiple globabl middlewares
Vue.use(MiddlewarePlugin, {
router,
middleware: [AuthMiddleware, LoggerMiddleware]
})
```
```javascript
import Vue from 'vue'
import MiddlewarePlugin from 'vue-router-middleware-plugin'
import router from '@/path-to-router'

> **Note:**: As the name suggests a global middleware will be resolved before each route.
Vue.use(MiddlewarePlugin, router)
```

Attach route middlewares in `router.js`
2. Create a middleware function.

```javascript
import ExampleMiddleware from './middlewares/example'
import AnotherMiddleware from './middlewares/another'
```javascript
import store from '@/path-to-store'

.
.
.
const routes = [
{
path: '/dashboard',
component: DashboardView,
meta: {
// attavh a middleware to a route
middleware: ExampleMiddleware
}
},
{
path: '/profile',
component: ProfileView,
meta: {
// you may also use an array for multiple middlewares
middleware: [ExampleMiddleware, AnotherMiddleware]
export default ({ to, from, redirect }) => {
if (!store.getters.isLoggedIn) {
redirect('/login')
}
}
},
.
.
.
]
```
```

> **Note**: Global middlewares have precedence over route middlewares
3. Attach middleware to a route.

If the user tries to access `/profile` route, the attached middlewares will be resolved in a synchronous order:
```javascript
import AuthMiddleware from '@/path-to-auth-middleware'

```bash
AuthMiddleware > LoggerMiddleware > ExampleMiddleware > AnotherMiddleware
```

`AuthMiddleware` and `LoggerMiddleware` will be resolved before profile route middlewares because they are global middlewares.
export default new VueRouter({
routes: [
{
path: '/',
meta: {
middleware: AuthMiddleware
},
.
.
},
```

Ignore global middlewares in `router.js`
Note: You may attach multiple middlewares to a route.

```javascript
import AuthMiddleware from './middlewares/auth'
import LoggerMiddleware from './middlewares/logger'
import ExampleMiddleware from './middlewares/example'
import AnotherMiddleware from './middlewares/another'

.
.
.
const routes = [
.
.
.
{
path: '/login',
component: LoginView,
meta: {
middleware: {
ignore: AuthMiddleware
}
}
middleware: [LoggerMiddleware, AnalyticsMiddleware]
},
.
.
},
{
path: '/register',
component: RegisterView,
meta: {
// you may also attach a middleware to this route
middleware: {
ignore: AuthMiddleware
attach: AnotherMiddleware
}
}
},

{
path: '/about',
component: AboutView,
meta: {
// you may also use an array for multiple middlewares
middleware: {
ignore: [AuthMiddleware, LoggerMiddleware]
attach: [ExampleMiddleware, AnotherMiddleware]
}
}
}
]
```

### New features

#### v1.2.0: Custom Middleware properties

You can now pass custom properties in plugin option `context` which will be accessible to the middleware.

```javascript
import Vue from 'vue'
import MiddlewarePlugin from 'vue-router-middleware-plugin'
import router from '~/router'
import store from '~/store'

Vue.use(MiddlewarePlugin, {
router,
// context must be an object
context: {
version: process.env.VERSION
}
})
```

In any middleware, `version` will be added to context

```javascript
export default ({ version }) => {
console.log('version:', version)
}
```

#### v2.0.0: New property in middleware context

* Middlewares don't need to be resolved by calling `next`.
* A new function `redirect`, added to the middleware context.
* **Breaking Change:** Function `next` removed from middleware context.

## Roadmap
Easy as that to get started.

* [x] **v1.0.0** - Route Middlewares.
* [x] **v1.1.0** - Global Middlewares.
* [x] **v1.2.0** - Middleware context - custom properties.
* [x] **v2.0.0** - Middleware Pipeline (rebuild).
* [ ] **v3.1.0** - Update context properties dynamically
:eyes: For advanced features like global middlewares and
middleware context continue to [Documentations](https://vue-router-middleware-plugin.netlify.com/).

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Pull requests are welcome. For major changes, please open an issue first to discuss
what you would like to change.

Please make sure to update tests as appropriate.

Expand Down
Empty file removed docs/.gitkeep
Empty file.
43 changes: 43 additions & 0 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module.exports = {
title: 'Vue Router Middleware Plugin',
description: 'The vue router middleware pipeline you deserve',
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide/' },
{ text: 'API', link: '/api/' },
{ text: 'GitHub', link: 'https://github.com/dsfx3d/vue-router-middleware-plugin'}
],
sidebar: {
'/guide/': [
{
title: 'Getting Started',
collapsable: false,
children: [
'',
'quickstart'
]
},
{
title: 'Advanced',
collapsable: false,
children: [
'configurations',
'context',
'middlewares'
]
}
],
'/api/': [
{
title: 'API Reference',
collapsable: false,
children: [
'',
'context',
'helpers'
]
}
]
}
}
}
15 changes: 15 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
home: true
heroText: Middleware Plugin
tagline: The middleware pipeline you deserve
actionText: Get Started →
actionLink: /guide/
features:
- title: Performant
details: Inspired from Nuxt Middlewares and built on top of vue router's Navigation Guards to offer the best of performance.
- title: Light-Weight
details: A light weight but powerful middleware pipeline to control logic between your routes.
- title: Extensible
details: The plugin API is inherently extensible to use within your applications or in integration with third-party plugins.
footer: MIT Licensed | Copyright © 2020 @dsfx3d
---
25 changes: 25 additions & 0 deletions docs/api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Options

These plugin options can be used to configure the plugin on registration.

```javascript
Vue.use(MiddlewarePlugin, {
router,
middleware,
context
})
```

## Options Properties

### `router: VueRouter`

The vue router instance of your app.

### `middleware?: function | Array<function>`

The middleware property is used to register global middlewares, it can be set to either a single middleware function or an array of middleware functions. _(optional)_

### `context?: object`

This option is used to add custom properties to the default middleware context. The context object is merged with the middleware context on plugin registration. _(optional)_
40 changes: 40 additions & 0 deletions docs/api/context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Context

```javascript
export default ({ app, to, from, redirect }) => {
if (to.path === '/protected') {
redirect(from)
} else {
const { visits } = app.$getMiddlewareContext()
app.$updateMiddlewareContext('visits', (visits || 0) + 1)
}
}
```

## Built-In Properties

The context has the following built-in properties:

### `app: VueConstructor`

A middleware app object with injected [helpers](helpers/).

### `to: Route`

The target [Route Object](https://router.vuejs.org/api/#the-route-object) being navigated to.

*An argument from [Navigation Guard](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards)*

### `from: Route`

The target [Route Object](https://router.vuejs.org/api/#the-route-object) being navigated from.

*An argument from [Navigation Guard](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards)*

### `redirect: function`

A function to redirect to any route. Accepts same arguments as the `next` function in a [Navigation Guard](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards) but unlike a navigation guard, it's not required to be called in each middleware in order to resolve it.

## Adding custom properties

In the above example, we appearently add a property `visits` to the middleware context. Goto [Helper Functions](helpers.html#functions) for more.
Loading