javascriptnode.jscallbackasynccallback

store data from database from call back


I am working on node js project, I am using ipstack to get user data from IP. can't understand how to get data from callback function and insert it into my database.

here is my code

const ipstack = require('ipstack');

const ip = '103.195.74.60';
ipstack(ip, process.env.IPSTACK, (err, response) => {
    console.log(response);
});

insert query here

// create user
await User.create({
    fullName,
    phone,
    email,
    nikeName,
    ip,
    city (come from ip),
    zip (come from ip),
    browser,
    device,
});

Solution

  • You can just need to make the database traction exactly where you are using the console.log call, as following:

    const ipstack = require("ipstack");

    const ip = "103.195.74.60";
    ipstack(ip, process.env.IPSTACK, (err, response) => {
      // First of all you need to check if there is error
      if (err){
        // handle error  hreer, you might need to use `return`
        // at some point to not execute the below code, alternatively 
        // you could just wrap it in `else`
                   }
        console.log(response); // your orginal `console.log` call
    
      //your  database transaction ca be done here,
      // create user
      
                await User.create({
                    fullName,
                    phone,
                    email,
                    nikeName,
                    ip,
                    response.city // need to look in documentation 
                    response.zip // or explore the response object terminal 
                    browser,
                    device,
                })
                
    });
    

    The part of code where I access the keys of response is speculation, you just need to look for documentation if exists for the ipstack package, or just by exploring the schema response given you are console.log.

    Lastly, I would suggest using the official documentation given the lipstick is not really maintained the last update was 3 years ago, add to that by following the official documentation you could use fetch or axios and take advantage of async await feature, which is the current modern method to handle asynchronous code*.

    *That might be an appointed perspective.