Search code examples
graphqlknex.js

How do I get the ID back from a knex insert?


Im using the code below as a part of a graphql resolver. I am trying to return the id back from the knex query but the console.log(pageid) is coming back as null.But the console.log(id) isn't;

resolve(parentValue, { id, page_name, page_type, page_category }) {
    var pageid = null;
    const pageInsert = knex
        .insert({ id, page_name, page_type, page_category })
        .returning('id')
        .into('page')
        .then(function (id) {
            console.log(id);
            pageid = id;
        });

    console.log(pageid);
    console.log(pageInsert);

    return pageInsert;
}

Solution

  • I will annotate the order how those lines are executed in javascript:

    resolve(parentValue, { id, page_name, page_type, page_category }) {
        var pageid = null;         // -- 1 page id is null
        const pageInsert = knex
            .insert({ id, page_name, page_type, page_category })
            .returning('id')
            .into('page')
            .then(function (id) {
                console.log(id); // -- 6 printing result just file
                pageid = id;     // -- 7 storing result to variable that is never used
            }); // -- 2 created query builder and triggered it's execution
    
        console.log(pageid);     // -- 3 pageid is still null
        console.log(pageInsert); // -- 4 page insert is a promise which is returned
    
        return pageInsert;       // -- 5
    }
    

    So you are getting it back in .then but then you are storing it to a local variable pageid and it is never used afterwards.

    You should probably do just:

    resolve(parentValue, { id, page_name, page_type, page_category }) {
        return knex
            .insert({ id, page_name, page_type, page_category })
            .returning('id')
            .into('page')
    }
    

    and in caller side:

    resolve(...).then(id => console.log(id))
    
    or
    
    const id = await resolve(...);