Skip to content

Commit 5ba9a74

Browse files
committed
feat: split out api function from api definition
define login and register routes
1 parent bfd0b02 commit 5ba9a74

File tree

2 files changed

+21
-15
lines changed

2 files changed

+21
-15
lines changed

src/api/index.js

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1+
import { inject } from 'vue'
12
const AUTH_KEY = 'auth'
23

3-
export default (appCache) => {
4-
return (path, opts) => {
5-
opts = opts || {}
6-
let auth = appCache.get(AUTH_KEY)
7-
let user = auth && auth.data ? auth.data : undefined
8-
if (user && user.token) {
9-
opts.headers = {
10-
...opts.headers,
11-
Authorization: `BEARER ${user.token}`
12-
}
4+
export default {
5+
login: opts => { return api('/api/login', opts) },
6+
register: opts => { return api('/api/register', opts)}
7+
}
8+
9+
const api = (path, opts) => {
10+
const $appCache = inject('$appCache')
11+
12+
opts = opts || {}
13+
let auth = $appCache.get(AUTH_KEY)
14+
let user = auth && auth.data ? auth.data : undefined
15+
if (user && user.token) {
16+
opts.headers = {
17+
...opts.headers,
18+
Authorization: `BEARER ${user.token}`
1319
}
14-
console.log(path, opts.headers)
15-
return fetch(`http://localhost:8080${path}`, opts)
16-
.then(res => res.ok ? res.json() : res)
1720
}
21+
console.log(path, opts.headers)
22+
return fetch(`http://localhost:8080${path}`, opts)
23+
.then(res => res.ok ? res.json() : res)
1824
}

src/composables/stores/auth.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export default {
3737
})
3838
}
3939

40-
$api('/api/login', opts)
40+
$api.login(opts)
4141
.then(dbUser => {
4242
$appCache.set(AUTH_KEY, dbUser)
4343
Object.assign(user, dbUser)
@@ -66,7 +66,7 @@ export default {
6666
})
6767
}
6868

69-
$api('/api/register', opts)
69+
$api.register(opts)
7070
.then(dbUser => {
7171
// Set user session if account is already confirmed (log the user in)
7272
if (!dbUser.confirm_token) {

0 commit comments

Comments
 (0)