passport add paramaters to request with nestjs javascript

I’m doing an application and I’m using “NestJS” for the back.

In my application, I have a button that allows the user to connect his Spotify account (using passport).

For the moment, when the user clicks on the button, I get the access token but I can’t stock it for now.

My problem is that I have no idea of how to tell my back which user clicked on the button, and how to stock the user id somewhere until I have the token. Here is my code :

In my front, I just have a button that redirects to my back :

const handleSpotifyButton = () => {
  window.location.href = "http://localhost:8080/auth/spotify";
};

I guess that I can pass an extra parameter like this :

window.location.href = "http://localhost:8080/auth/spotify?userId=${userId}";

But then, I don’t know how to use it in my back. Here is my controller :

import { SpotifyAuthGuard } from "./spotify-auth.guard";
import { Controller, Get, Request, UseGuards } from "@nestjs/common";
import { SpotifyService } from "./spotify-auth.service";
import { Redirect } from "@nestjs/common";

@Controller("auth")
export class SpotifyController {
  constructor(private spotifyService: SpotifyService) {}

  @Get("spotify")
  @UseGuards(SpotifyAuthGuard)
  async spotifyAuth() {}

  @Get("spotify-redirect")
  @Redirect("http://localhost:8081")
  @UseGuards(SpotifyAuthGuard)
  spotifyAuthRedirect(@Request() req) {
    this.spotifyService.spotifyLogin(req);
  }
}

Here I could get the parameter in the route “spotify”, but then I don’t really know how it works to open the spotify authorization window.

The ideal would be to get it in my service, where I print the token, so I could just add it in my database from here :

import { Injectable } from "@nestjs/common";

@Injectable()
export class SpotifyService {
  async spotifyLogin(req): Promise<string> {
    if (!req.user) {
      return "No user from spotify";
    }
    const spotifyUser = req.user;
    console.log(spotifyUser.accessToken);
    return spotifyUser;
  }
}

Here is my guard :

import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class SpotifyAuthGuard extends AuthGuard("spotify") {
  constructor(private configService: ConfigService) {
    super({
      accessType: "offline",
    });
  }
}

My module :

import { SpotifyAuthStrategy } from "./spotify-auth.strategy";
import { Module } from "@nestjs/common";
import { SpotifyController } from "./spotify-auth.controller";
import { SpotifyService } from "./spotify-auth.service";
import { ConfigModule } from "@nestjs/config";

@Module({
  imports: [ConfigModule.forRoot()],
  controllers: [SpotifyController],
  providers: [SpotifyService, SpotifyAuthStrategy],
})
export class SpotifyAuthModule {}

And my strategy :

import { PassportStrategy } from "@nestjs/passport";
import { Strategy, VerifyCallback, Profile } from "passport-spotify";
import { Injectable } from "@nestjs/common";

@Injectable()
export class SpotifyAuthStrategy extends PassportStrategy(Strategy, "spotify") {
  constructor() {
    super({
      clientID: "myClientId",
      clientSecret: "myClientSecret",
      callbackURL: "http://localhost:8080/auth/spotify-redirect",
      scope: ["user-library-read", "user-library-modify"],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: Profile,
    done: VerifyCallback,
  ): Promise<any> {
    try {
      const { id, displayName, emails } = profile;

      const user = {
        id,
        displayName,
        email: emails ? emails[0].value : null,
        accessToken,
        refreshToken,
      };

      done(null, user);
    } catch (error) {
      done(error, null);
    }
  }
}

Ask me if you need more informations about my code

Thanks

In VS code extension how to make wait, input box is needed to wait until input is given if we click somewhere on screen

Problem:

I have added Quick Pick list drop down to command palette. Now i click on screen anywhere accidently,
Command palette input is skipping to next without taking inputs for current.

Tried:

I have tried by waiting till input is given by await, but it is not stopping.

Expecting:

Command palette should wait till input is given and should not move to next if we click on screen or some other place.

Set default magic type for react echarts

 toolbox: {
                feature: {
                    restore: {
                        show: true
                    },
                    magicType: {
                        show: true,
                        type: ['line', 'bar']
                    },

This configuration by default renders a line graph and allows for switching to the bar via click on the bar icon in the toolbox.
But what if I want the default selected type to be bars?

The actual issue Im having actually is that I want the default graph to be lines, like it is, BUT the line icon IS NOT rendering as selected (highlighted blue), rather it looks unselected.

If I click the line graph, even though it already was line graph, the icon becomes highlighted blue and the graph stays the same.

How can I make the icon be blue from the get go to emphasize the default selected type?

trying to stream line ai response and I have this error “getReader() is not a function”

Hi everyone I’m trying to streamline the ai response and I get this error on my function, anyone have any idea on how to fix it?

  let result;
  try {
    const response = await REQUEST({
      method: 'POST',
      url: CHATBOT_NEW,
      data: data,
      auth: true,
    });
    console.log('+++response.data+++', response.data);
    const reader = response?.data?.getReader(); // here is the bug
    let chunks = '';

    while (true) {
      const { done, value } = await reader?.read();
      if (done) {
        console.log('Completed fetching data');
        break;
      }
      chunks += new TextDecoder('utf-8').decode(value);
    }

    result = chunks;
  } catch (error) {
    console.log(error);
  }
  console.log('+++result+++', result);
  return result;
}; ```

Why there is not already a reimplemented version of JavaScript? [closed]

JavaScript is known for having a lot of flaws in its current state:

  • Because of the rule “Don’t break the web” it’t contains a lot of deprecated and dangerous stuff
  • No native multithreading
  • … etc ???

So I’m wondering, why there is not already a new version of JS or it’s successor solving all these issues.

This is how I understand the way JS is developed and used nowadays: The state of JS is directed by ES standard that is then implemented into an engine. These engines are run either on the client side (browser) or on the server (e.g. Node.js).
I understand that it’s necessary to persist the current engines to keep the current solutions on the web working.

But what if it was possible to switch between the current engine and the reimplemented engine (e.g in header metadata of index.html, …)? Then the current stuff would be still working and the new one would use the better version of JS.

Leaving aside expenses for creating a new engine and maintain the old one: What are another reasons why there is no such solution as described above?

How to use block attributes in view.js in WP?

I tried the new npm package @wordpress/create-block to generate custom blocks in WordPress.

The file view.js was created automatically in my blocks folder. In the view.js i can write JavaScript Code for my custom block.

Now i want to use the block attributes in view.js but i cannot find in wp docs how to pass the information into my view.js file?

I placed the attributes in block.json.

"attributes": {
    "content": {
        "type": "string",
        "source": "html",
        "selector": "h2",
    },
    "question": {
        "type": "string",
        "source": "html",
        "selector": "div",
    },
    "autoplay": {
        "type": "boolean",
    },
    "loop": {
        "type": "boolean",
    },
},

How can i use for e.g. the attributes.autoplay or attributes.loop in view.js?

closed property of child is becoming true even child is not closed in chrome

I am trying to listening to closed property of child in chrome but closed is becoming true even without closing the child tab. Below is the code I am using to achieve my task

    var child = window.open(
      "http://localhost:5001/auth/google",
      "",
      "location=yes,status=yes,width=1366,height=768"
    );
    setInterval(() => {
      console.log(child);
      if (child === null || child.closed) {
        clearInterval(clearTimeout);
        console.log("THE CHILD WINDOW HAS BEEN CLOSED");
      } else {
        console.log("OK");
      }
    }, 1000);

Next.js API not working in production mode

I am building a electron app using next.js so that I have used Nextron framework for that.

THe issue I am facing is the API that I have created inside the next.js app are working perfectly in the local or development mode but when I build the app for the production it does not work.

my code as follows :

DATABASE

const Database = require('better-sqlite3');

// Create SQLite database instance
const db = new Database('dev.db');

// Define a User table
const createUserTable = db.prepare(`
    CREATE TABLE IF NOT EXISTS User (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        email TEXT UNIQUE
    )
`);

// Run the table creation query
createUserTable.run();

// Example: Insert a user into the User table
const insertUser = db.prepare('INSERT INTO User (name, email) VALUES (?, ?)');
insertUser.run('John Doe', '[email protected]');

// Example: Query all users from the User table
const getAllUsers = db.prepare('SELECT * FROM User');
const users = getAllUsers.all();

console.log(users);

// Close the database connection
db.close();

HOME.JSX

import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import Image from 'next/image';

export default function HomePage() {
  const [message, setMessage] = useState('No message found');
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch data from the API when the component mounts
    fetch('/api/users/')
      .then((response) => response.json())
      .then((data) => setUsers(data))
      .catch((error) => console.error('Error fetching data:', error));

    // Set up IPC listener
    window.ipc.on('message', (ipcMessage) => {
      setMessage(ipcMessage);
    });

    // Clean up IPC listener on component unmount
    return () => {
      window.ipc.removeListener('message', handleMessage);
    };
  }, []); // Empty dependency array ensures the effect runs only once on mount

  return (
    <React.Fragment>
      <Head>
        <title>Home - Nextron (basic-lang-javascript)</title>
      </Head>
      <div>
        <p>
          ⚡ Electron + Next.js ⚡ -
          <Link href="/next">
            <a>Go to next page</a>
          </Link>
        </p>
        <Image
          src="/images/logo.png"
          alt="Logo image"
          width="256px"
          height="256px"
        />
      </div>
      <div>
        <button
          onClick={() => {
            window.ipc.send('message', 'Hello');
          }}
        >
          Test IPC
        </button>
        <p>{message}</p>

        <h2>Users:</h2>
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.name} - {user.email}</li>
          ))}
        </ul>
      </div>
    </React.Fragment>
  );
}

BASIC CONTROLLER CRUD

import sqlite from 'better-sqlite3';

// Open SQLite database connection
const db = sqlite('dev.db');

export default async function handler(req, res) {
    if (req.method === 'GET') {
        try {
            const users = db.prepare('SELECT * FROM User').all();
            res.status(200).json(users);
        } catch (error) {
            console.error(error);
            res.status(500).json({ error: 'Internal Server Error' });
        }
    } else if (req.method === 'POST') {
        const { name, email } = req.body;
        try {
            const insertUser = db.prepare('INSERT INTO User (name, email) VALUES (?, ?)');
            const result = insertUser.run(name, email);

            res.status(201).json({ id: result.lastInsertRowid });
        } catch (error) {
            console.error(error);
            res.status(500).json({ error: 'Internal Server Error' });
        }
    }
}

GET THIS ERROR IN THE CONSOLE

DIRECTORY

At what time fetch resolves promise

I read on MDN that the returning promise of fetch resolves “as soon as the server responds with headers”.
What does this means?
Does it resolve before I receive any body data?
But why is the body data available as soon as the fulfilled callback function is called?

enter image description here

karate – how to check the status of id’s captured from response of API call using JS function?

Scenario: I read 20 messages from data.json file and posted them using rest API call. I get UUID within the response which I am storing in postIds array. After I read and post all 20 messages, I need to wait for 3 minutes, like one time where the batchjob job picks up the data and process them and then check the status for each postId. if its passed its success and if its failed the test failed. How do it do it? either my query runs without errors but no proper output or I always get syntax errors.

Background:
    * def oldfirstname = 'abcdef'
    * def oldlastname = 'def'
    * call read('Token.feature')
    * header Authorization = 'Bearer ' + token
    * def config = karate.call('classpath:karate-config.js')
    * def FakerHelper = Java.type('com.API.FakerHelper')
    * def randomFirstName = FakerHelper.getRandomFirstName()
    * def randomLastName = FakerHelper.getRandomLastName()
    * configure retry = { count: 3, interval: 90000 }
    * def Thread = Java.type('java.lang.Thread')
    * def postIds = []

  @post11
  Scenario Outline: Batch Post Messages
    * header Content-Type = 'text/plain'
    * url apiurl
    * def hMessage = data
    * def modifiedmsg = hMessage.replace(oldfirstname, randomFirstName)
    * def modifiedData = modifiedmsg.replace(oldlastname, randomLastName)
    * request modifiedData
    When method POST
    Then status 200
    * def postId = response
    * print postId
    * eval karate.appendTo('postIds', postId)
    * print postIds

    Examples:
      | read('data.json') |

@checkStatus
Scenario: Check status of all messages after 3 minutes
  * def checkStatus =
"""
function(postId) {
  var fullUrl = checkstatusurl + postId;
  var response = karate.get(fullUrl);
  karate.log('Post ID: ' + response. postId + ', Status: ' + response.status);
"""
  * eval Thread.sleep(180000)
  * def storedPostIds = karate.get('postIds')
  * karate.forEach(storedPostIds, checkStatus)

Understanding constructors in JS class

I am trying have a class that restructures the parameters passed to the constructor in a way that is not just assigning it to its own this instance, so that:

class Test {
  constructor(a, b, c){
    this.a = a;
    this.dict = { b: b, c: c };
  }
}

The instance is built from an ajax query via Object.assign which passes the a, b, c.
unfortunately this doesn’t seem to work, and I get it instead initialized this way:

Test{
a:a, // works obviously
b:b, // wrong
c:c, // wrong
dict:{a: undefined,b:undefined} // wrong
}

What am I misunderstanding about how to use constructors here?

How to use a single script for my 2 html file

i want to ask if it is possible to use a single JavaScript file on 2 different html file?

what i do is i create a 2 html file named index.html and seller.html and i used the

<script src="/scripts/app.js"></scrip>

on both html file. however it seems it doesn’t work.

PHP: Getting nested div containers in the html page

My PHP code is designed to display content on an HTML page. The functionality involves iterating through an array of objects using a foreach loop. For each unique ID in the array, a new class is dynamically generated. The intention is to display the corresponding div container when a specific ID is selected from a dropdown menu.

However, there’s an issue: instead of obtaining separate div containers for each ID, I’m experiencing nested div containers. This problem is affecting the functionality of my code to display the selected ID. Below are snippets of my code

Code Snippet

<?php
    // chart loader required for signal history graphs
    set_html_head('<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>');
    add_css('sites/all/themes/clean/pages/stylesheets/diagnostics.css');
    add_js('sites/all/themes/clean/pages/js/helpers.js');
    add_js('sites/all/themes/clean/pages/js/speed-test-results.js');
    $data = $vars['data'];
    $mf_models = unserialize(models);
?>

<div id="diagnostics-wrap">
    <div id="cs-cd-header">
        <h2>Support Page</h2>
        <h3>User ID: <?php print $vars['user_id'] ?></h3>
        <div></div>
        <a href="/admin/service/<?php print $vars['user_id'] ?>">(Service Record)</a> <a href="/admin/service/resend_email/<?php print $vars['user_id'] ?>">(Resend Email)</a>
        <select id="location-selector" onchange="change(this)">
            <option value="all-locations" selected="selected">All Locations</option>

        <?php foreach ($vars['service_locations'] as $key => $sid):?>

            <option value="<?php
                    print $key; ?>">
                <?php
                print $sid['street1']; ;?>
            </option>
        <?php endforeach; ?>
        </select>
    </div>

<?php if ($data === FALSE): ?>
    <h1>Unable to connect</h1>
<?php elseif ($data): ?>
<?php
foreach ($data->data as $cam): ?>
    <?php
        $everything = json_decode(get_everything($cam->uuid));
        $is_shield = $cam->model === 'TEST123';
        $dataVar = stringer($cam->name_id) . rand(1, 999999999);
        include('sites/all/themes/clean/pages/diagnostics-signal-chart-builder.php');
        // js to be ran for battery signal
        if ($everything->model == array_search('search', $mf_models)) {
          include('sites/all/themes/clean/pages/diagnostics-battery-chart-builder.php');
        }
    ?>

    <div class="each-data <?php print $cam->sid;?>">
        <div class="header-wrapper">
            <h3><?php print ucfirst($cam->settings->name) .  '<span> uuid: ' . substr($cam->uuid, -7, 7) . '</span>'; ?></h3>
          <br>
          <span>Model: <?php print $model_name; ?></span>
         </div>

        <br />
       
      <?php if ($is_shield) :?>
        <div class="speed-data-history-wrapper info" style="width: 48%; margin: auto;">
            <h2 class="settings-header">Speed Test History</h2>
            <div class="signal-chart"
                 id="<?php print $cam->uuid . '-speed-graph'; ?>"
            >
            </div>
        </div>
      <?php endif; ?>
        <?php if($is_shield): ?>
        <div>
            <div class="battery-history-wrapper info" style="width: 48%; margin: auto;">
                <h2 class="settings-header">Battery History</h2>
                <div class="signal-chart"
                     id="<?php print ($dataVar . '-battery-graph'); ?>"
                >
                  <?php if (count($battery) < 1): ?>
                      <span class="unknown">Unavailable</span>
                  <?php endif; ?>
                </div>
        </div>
        <br/>
        <div>
            <span style="color:red"><?php print $error_message; ?></span>
        </div>
        <?php endif; ?>


        <?php
          $has_perm = array_intersect(array('developer'), $GLOBALS['user']->roles);
          if ($everything->model == array_search('search', $mf_models)) :
        ?>
        <br/>
        <div class="battery-history-wrapper info" style="width: 48%; margin: auto;">
            <h2 class="settings-header">Battery History</h2>
            <div class="signal-chart"
                 id="<?php print ($dataVar . '-battery-graph'); ?>"
            >
              <?php if (count($battery) < 1): ?>
                <span class="unknown">Unavailable</span>
              <?php endif; ?>
            </div>
        </div>
            <?php if ($has_perm) : ?>
            <div>
                <button class="button" value="<?php print $cam->uuid; ?>" onclick="addTrial('<?php print $cam->uuid; ?>',<?php print $vars['user_id'] ?>,<?php print $cam->sid;?>)">Add Free Trial</button>
            </div>
          <?php endif; ?>

        <?php endif; ?>

        <div class="clear"></div>
        <hr>
    </div>

<?php endforeach; ?>
<?php else: ?>
    <h1>No data</h1>
<?php
    endif;
?>


</div>

Change function

function change(obj) {
    var value = $(obj).val();
    if ( value == 'all-locations') {
        $('.each-data').show();
    } else {
        $('.each-data').hide();
        $('.' + value).show();
    }
}

At which place the issue is coming and what can I do here to resolve this?

I tried to check all the div tags if it is properly closed. Then I checked the change function if it is creating any issue in displaying.