Skip to content

Commit

Permalink
Refactor registerUser function and import registerUser from utils/reg…
Browse files Browse the repository at this point in the history
…ister.ts
  • Loading branch information
Arejula11 committed Apr 3, 2024
1 parent ef747e4 commit 4baa107
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 20 deletions.
35 changes: 15 additions & 20 deletions playbeat/src/pages/register.astro
Original file line number Diff line number Diff line change
@@ -1,25 +1,10 @@
---
import NormalLayout from '../layouts/NormalLayout.astro'
const errors = { username: "", email: "", password: "" };
import {registerUser} from '@/utils/register.ts'
const errors = { username: "", email: "", password: "", peticion:"" };
const values = { username: "", email: "", password: "", password2:"" };
async function registerUser(data: { name: FormDataEntryValue | null; email: FormDataEntryValue | null; password: FormDataEntryValue | null; }) {
try {
console.log(data);
const response = await fetch('', {
method: 'POST',
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Error al registrar usuario');
}
return response.json();
} catch (error) {
throw new Error((error as Error).message);
}
}
Expand Down Expand Up @@ -59,10 +44,18 @@ if (Astro.request.method === "POST") {
}
// Do something with the data
const hasErrors = Object.values(errors).some(msg => msg)
if (!hasErrors) {
await registerUser({name, email, password});
console.log("Usuario registrado");
if (!hasErrors) {
const response = await registerUser({name, email, password});
console.log(`Response: ${response}`)
if (response && response.ok == true) {
console.log("Registrado");
const data = await response.json();
const token = data.token;
Astro.cookies.set("token", token);
return Astro.redirect("/");
} else {
errors.peticion = "Error al registrar, intentelo de nuevo";
}
}
} catch (error) {
if (error instanceof Error) {
Expand Down Expand Up @@ -102,6 +95,8 @@ if (Astro.request.method === "POST") {
<p class="text-white ">{errors.username}</p>
<p class="text-white ">{errors.email}</p>
<p class="text-white ">{errors.password}</p>
<p class="text-white ">{errors.peticion}</p>

</div>
}

Expand Down
20 changes: 20 additions & 0 deletions playbeat/src/utils/register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import {Global} from "@/globalState/globalUrl.js"


async function registerUser(data: { name: FormDataEntryValue | null; email: FormDataEntryValue | null; password: FormDataEntryValue | null; }) {
try {
console.log(data);
const response = await fetch(Global.url+'auth/signup', {
method: 'POST',
body: JSON.stringify(data)
});
console.log(response);
return response;
} catch (error) {
throw new Error((error as Error).message);
}
}


export {registerUser}

0 comments on commit 4baa107

Please sign in to comment.