Extracted gateway for requests
This commit is contained in:
@@ -1,18 +1,17 @@
|
||||
<script setup>
|
||||
import {ref} from "vue";
|
||||
import {$user} from "./stores/user.js";
|
||||
import * as gateway from "./lib/gateway.js";
|
||||
|
||||
const formData = ref({username: '', password: ''})
|
||||
|
||||
async function formSubmit() {
|
||||
const url = `${import.meta.env.PUBLIC_SERVER_URL}/login`
|
||||
const response = await fetch(
|
||||
url,
|
||||
const response = await gateway.request(
|
||||
'/login',
|
||||
{
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
body: JSON.stringify(formData.value),
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
cors: true,
|
||||
body: JSON.stringify(formData.value)
|
||||
}
|
||||
)
|
||||
if(response.status === 200) {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
export async function request(path, options) {
|
||||
options ||= {}
|
||||
if(path.startsWith('/')) {
|
||||
path = path.slice(1)
|
||||
}
|
||||
|
||||
let url = new URL(path, import.meta.env.PUBLIC_SERVER_URL)
|
||||
let searchParams = new URLSearchParams(options.searchParams)
|
||||
searchParams.forEach((v, k) => url.searchParams.append(k, v))
|
||||
|
||||
const safeFetch = (options.method === 'GET') || (options.method === 'HEAD')
|
||||
const authorization = (options.token) ? `Bearer ${options.token}` : null
|
||||
|
||||
const fetchInit = {
|
||||
method: options.method || 'GET',
|
||||
body: options.body,
|
||||
mode: options.cors ? 'cors' : undefined,
|
||||
credentials: options.cors ? 'include' : undefined,
|
||||
headers: {
|
||||
'Content-Type': options.contentType ||
|
||||
(safeFetch ? null : 'application/json'),
|
||||
'Authorization': authorization
|
||||
}
|
||||
}
|
||||
|
||||
return await fetch(url, fetchInit)
|
||||
}
|
||||
Reference in New Issue
Block a user