amrnn90 / breeze-nuxt

An application / authentication starter kit frontend in Nuxt3 for Laravel Breeze.
MIT License
198 stars 33 forks source link

How to use $larafetch in server? #13

Closed carlosvaldesweb closed 1 year ago

carlosvaldesweb commented 1 year ago

Hello, i'm trying to use $larafetch in server api /server/api/submit.ts, but i can't. Im trying to import like this import { $larafetch } from "../../../utils/$larafetch";

But i'm getting an error

[nuxt] [request error] [unhandled] [500] useRouter is not defined
  at $larafetch (./utils/$larafetch.ts:29:1) 

I'm trying to check if user is authenticated directly from laravel server, to after run any code in nuxt server.

amrnn90 commented 1 year ago

I haven't actually tried using api routes in Nuxt, you already have a full-fledged Laravel backend, why not just use it for whatever you are trying to do?

carlosvaldesweb commented 1 year ago

I'm trying to implement open AI Api. I want to return a streamed response from Nuxt server, because it is more easy to do with node that with laravel. So i want to check if user is subscribed before to call Open AI Api.


const response = $larafetch("/user/subscribed", {
options
});

if ( !response.is_subscribed ) {
return'You dont have access to this feature';
}

const stream = await OpenAI(
    "chat",
    {
      model: "gpt-3.5-turbo",
      messages,
      stream: true,
    },
    {
      apiKey: "xxxx",
    },
  );
  return sendStream(event, stream);

Also i want to create a server middleware to protect this api routes.

amrnn90 commented 1 year ago

Can you please pull the latest commits and see if your issue is fixed? You will have to pass the h3 event to $larafetch like this:

// server/api/hello.ts

import { $larafetch } from "../../utils/$larafetch";

export default defineEventHandler(async (event) => {
  return await $larafetch("/api/user", {
    event
  });
});
amrnn90 commented 1 year ago

You should be able to do it now like this:

// server/api/hello.ts

import { createApiLarafetch } from "../../utils/$larafetch";

export default defineEventHandler((event) => {
  const apiLarafetch = createApiLarafetch(event);

  return apiLarafetch("/api/user");
});

Feel free to open a new issue if you are still facing problems.

carlosvaldesweb commented 1 year ago

Thank's for quickly reply, i'll test it and comment if i find some error.

amrnn90 commented 1 year ago

Hi @carlosvaldesweb, you can now use $larafetch normally in Nuxt server routes.