#the script takes the variable 1 time

95 messages · Page 1 of 1 (latest)

hidden summit
#

Hi, please help, this code loads a variable with a token only 1 time, and with further updating of values in the database, the old value remains in the code. I want to make sure that every time the API is requested, the script takes a new value.

const db = new sqlite3.Database('database.db');

interface Row {
  token: string;
}

const getCookieFromDatabase = () => {
  return new Promise<string>((resolve, reject) => {
    db.get('SELECT token FROM cookies LIMIT 1', (err, row: Row) => {
      if (err) {
        reject(err);
      } else {
        console.log(row)
        resolve(row?.token || '');
      }
    });
  });
};

const newSunoApi = async () => {
  const cookie = await getCookieFromDatabase();
  const sunoApi = new SunoApi(cookie);
  return await sunoApi.init();
};

export const sunoApi = newSunoApi();
flat lynx
#

'SELECT token FROM cookies LIMIT 1'
this is not a correct query for grabbing a token

id token
1  abcabc
2  bcdbcd
3  cdecde

you will always grab the first row 1 abcabc with that query

SELECT token FROM cookies WHERE id = 2

now this grabs 2 bcdbcd

hidden summit
flat lynx
#

you can't share a cookie for all users

#

the cookie is stored on the user's browser

#

you use that data to retrieve its associated data

#

cookie on browser(1234) -> lookup db table for 1234 -> { some: data }

hidden summit
#

my token is updated only after the restart, I can show the full code

flat lynx
#

the query is still a problem. every user cannot share the same cookie

#

cookie on browser(1234) -> SELECT * FROM cookies LIMIT 1 -> { id: 1 }
cookie on browser(9876) -> SELECT * FROM cookies LIMIT 1 -> { id: 1 }

hidden summit
#

what should I do in this case?

flat lynx
#

you need to add a WHERE to the query

#

which means that the function sending the query needs to accept a parameter

#
findTokenById(id) => [..] WHERE id = id
hidden summit
#

I have only 1 column in the database, so there is no point in using where

flat lynx
#

and what happens when more users connect?

#

what happens when the cookie is removed from the db?

#

returning the first row is by no way future proof

hidden summit
#

only 1 record is stored in the database, and it will be

flat lynx
#

is it a local database for a single user?

hidden summit
#

ye

#

I need help getting the token loaded every time there is an API request, not just at startup

drifting garnet
#

Can you query the database for the value every time you use it?

flat lynx
#

export const sunoApi = newSunoApi();
i think the file that imports this will need to be reloaded each time you want the data to be updated

#

how are you using it?

hidden summit
hidden summit
# flat lynx how are you using it?
import { NextResponse, NextRequest } from "next/server";
import { sunoApi } from "@/lib/SunoApi";
import { corsHeaders } from "@/lib/utils";

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  if (req.method === 'GET') {
    try {

      const limit = await (await sunoApi).get_credits();


      return new NextResponse(JSON.stringify(limit), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
          ...corsHeaders
        }
      });
    } catch (error) {
      console.error('Error fetching limit:', error);

      return new NextResponse(JSON.stringify({ error: 'Internal server error. ' + error }), {
        status: 500,
        headers: {
          'Content-Type': 'application/json',
          ...corsHeaders
        }
      });
    }
  } else {
    return new NextResponse('Method Not Allowed', {
      headers: {
        Allow: 'GET',
        ...corsHeaders
      },
      status: 405
    });
  }
}

export async function OPTIONS(request: Request) {
  return new Response(null, {
    status: 200,
    headers: corsHeaders
  });
}
flat lynx
#

ok so if you hit that GET endpoint you get the data

#

if you update the data in the db and hit the GET endpoint again, the data is not changing?

hidden summit
#

ye

flat lynx
#

ok so we're gonna do a bit of debugging just to confirm something first

#

in the GET function try returning JSON.stringify({ date: new Date()).toString() })

#

hit the endpoint a few times and just check it's not a cache issue

hidden summit
#

I'll try it now

flat lynx
#

and did you follow a guide to set up SunoApi? can you link it

hidden summit
#

In the original, the token is taken from .env, but I'm rewriting it under sqlite3 so that the token is taken from there.

hidden summit
flat lynx
#

if it changes then there is no cache and we can eliminate that as a problem

hidden summit
#

the value changes only on restart, does not change anymore

flat lynx
#

so the date stamp is the same?

hidden summit
#

when I started, I had one value, I refreshed the page, it was the same. Then I changed this value in the database and it also changed. There were no changes to the api in subsequent database updates

flat lynx
#

Then I changed this value in the database and it also changed.
but that means it's working doesn't it?

#

does the data reflect the current database data?

hidden summit
#

The timestamps change every time the page is refreshed

hidden summit
flat lynx
#

what are the screenshots of

hidden summit
flat lynx
#

where's the console log coming from i mean

hidden summit
#

cmd

flat lynx
#

did you write the console.log inside the GET func?

#

or is that some stamp for each request

#

have you got a github repo of this i could look at

hidden summit
#

yes

#

I only changed the end

#

on

#
interface Row {
  token: string;
}

const getCookieFromDatabase = () => {
  let db = new sqlite3.Database('database.db');
  return new Promise<string>((resolve, reject) => {
    db.get('SELECT token FROM cookies', (err, row: Row) => {
      if (err) {
        reject(err);
      } else { 
        console.log(row)
        resolve(row?.token || '');
      }
    });
  });
};

const newSunoApi = async () => {
  const cookie = await getCookieFromDatabase();
  const sunoApi = new SunoApi(cookie);
  return await sunoApi.init();
};

export const sunoApi = newSunoApi();
flat lynx
#

try export newSunoApi

hidden summit
flat lynx
#

you have a function using that, just export it

#
const newSunoApi = async () => {
  const cookie = await getCookieFromDatabase();
  const sunoApi = new SunoApi(cookie);
  return await sunoApi.init();
};

this one

#

just export it

#

then import it in the GET func

hidden summit
#

I didn't understand a bit

flat lynx
#
-const newSunoApi = async () => {
+export const newSunoApi = async () => {
  const cookie = await getCookieFromDatabase();
  const sunoApi = new SunoApi(cookie);
  return await sunoApi.init();
};
#
import { newSunoApi } from '@/lib/SunoApi'
export async function GET(req: NextRequest) {
  if (req.method === 'GET') {
    try {
      const suno = newSunoApi()
      const limit = suno.get_credits();
      return new NextResponse(JSON.stringify(limit), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
          ...corsHeaders
        }
      });
#

try that

hidden summit
#

so?

flat lynx
#

what's the error

hidden summit
flat lynx
#

what's the type of suno

hidden summit
flat lynx
#

seems like you might need to do const suno = await newSunoApi()?

hidden summit
#

what?

flat lynx
#

you declared a suno

#

add await

hidden summit
#

yes

flat lynx
#
-const suno = newSunoApi()
+const suno = await newSunoApi()

does that fix it

hidden summit
#

or so?

flat lynx
#

no not there

#

inside the GET func

flat lynx
#

L10-11

hidden summit
#

all

#

everything is working, thank you very much

flat lynx
#

ok so your problem was that

export const sunoApi = newSunoApi();

made a closure over your class

#

you don't want to do that