Skip to content

Questions about v3.6.0 #191

Closed
Closed

Description

@wravery

Thank you Bill Avery (@wravery) . after changing that modification in my make file. I am getting the output without the error of the HelloClient program. Please check my question also in stackoverflow. In your samples of cppgraphiql doesn't run with dependency of electron-cppgraphql. Other than that. In my project we were using Napi.h. How to rewrite your samples for TodayMock with Napi.h. I am creating HelloMock like TodayMock from samples code placed in project directory. I commented Napi.h codings in "hello.cpp". But in this time i got the following errors

makefile

CFLAGS = -Os -O3 -fPIC -Ofast -std=gnu++17

CC = gcc
CXX = g++

LDFLAGS := \
	-pthread \
	-rdynamic

DEFS := \
	'-DUSING_UV_SHARED=1' \
	'-DUSING_V8_SHARED=1' \
	'-DV8_DEPRECATION_WARNINGS=1' \
	'-DV8_DEPRECATION_WARNINGS' \
	'-DV8_IMMINENT_DEPRECATION_WARNINGS' \
	'-D_LARGEFILE_SOURCE' \
	'-D_FILE_OFFSET_BITS=64' \
	'-DOPENSSL_NO_PINSHARED' \
	'-DOPENSSL_THREADS'	\
	'-D__STDC_FORMAT_MACROS' \
	'-DNAPI_DISABLE_CPP_EXCEPTIONS' \
	'-DBUILDING_NODE_EXTENSION'

# Flags passed to all source files.
GYP_CFLAGS := \
	-frtti \
	-fexceptions \
	-pthread \
	-Wall \
	-Wextra \
	-Wno-unused-parameter \
	-fno-omit-frame-pointer

# Flags passed to only C files.
CFLAGS_C :=

# Flags passed to only C++ files.
CFLAGS_CC := \
	-std=gnu++1y \
	-fexceptions

INC_NAPI := -I/usr/include/node-addon-api
INC_NODE := -I/usr/include/node
# INC := -I./separate
# INC := -I./separate -I../cppgraphqlgen/include -I../cppgraphqlgen/PEGTL/include

# INC_NAPI = -I/usr/lib/node_modules/node-addon-api
# INC_NODE := -I/usr/include/node

CGI_LIB = -lcgicc

# LIBS := /home/jeya/cpp-graphql-projects/cppgraphqlgen/src
LIBS := /usr/local/lib
GRPHQL := -L${LIBS}/libgraphqlclient.a -L${LIBS}/libgraphqljson.a  -L${LIBS}/libgraphqlintrospection.a  -L${LIBS}/libgraphqlservice.a  -L${LIBS}/libgraphqlresponse.a  -L${LIBS}/libgraphqlpeg.a
NOTH_A = nothing.a

# OBJ = nothing.o ./today/sampleQryParse.o ./hello/HelloClient.o ./hello/hello.o

# ENODE = ${NOTH_A} ./today/sampleQryParse.node ./hello/HelloClient.node ./hello/hello.o

OBJ = nothing.o ./hello/HelloClient.o

ENODE = nothing.a ./hello/HelloClient.node ./hello/hello

# GREET_DEMO = ./greet-demo
# CLASS_DEMO = ./class-demo
DEMO := ./today
HELLO := ./hello
target: ${OBJ} ${ENODE}

clean:
	rm -rf *.o *.node *.a
	rm -rf ${DEMO}/*.o ${DEMO}/*.node
	rm -rf ${HELLO}/*.o ${HELLO}/*.node

./today/sampleQryParse.o: ./today/sampleQryParse.cpp
	${CXX} ${CFLAGS} -shared '-DNODE_GYP_MODULE_NAME=sampleQryParse' ${GYP_CFLAGS} ${INC_NODE} ${INC_NAPI} -c $< -o $@

./today/sampleQryParse.node: ./today/sampleQryParse.o
	${CXX} -shared -Wl,-soname=sampleQryParse.node -Wl,--start-group ./today/sampleQryParse.o ${NOTH_A} ${GRPHQL} -Wl,--end-group -o $@

./hello/hello.o: ./hello/hello.cpp
	${CXX} ${CFLAGS} '-DNODE_GYP_MODULE_NAME=hello' ${DEFS} ${GYP_CFLAGS} ${INC_NAPI} ${INC_NODE} -c $< -o $@

./hello/hello.node: ./hello/hello.o
	${CXX} ${CFLAGS} ./hello/hello.o -shared -Wl,-soname=hello.node -Wl,--start-group -lpthread ${GRPHQL} ${NOTH_A} -Wl,--end-group -o $@

./hello/hello: ./hello/hello.cpp
	${CXX} ${CFLAGS} ./hello/hello.cpp -shared -Wl,-soname=hello -Wl,--start-group -lpthread ${GRPHQL} -Wl,--end-group -o $@

# ./hello/HelloClient: ./hello/HelloClient.cpp
# 	${CXX} ${CFLAGS} $< -o $@

./hello/HelloClient.o: ./hello/HelloClient.cpp
	${CXX} ${CFLAGS} '-DNODE_GYP_MODULE_NAME=HelloClient' ${DEFS} ${GYP_CFLAGS} ${INC_NAPI} ${INC_NODE} -c $< -o $@

./hello/HelloClient.node: ./hello/HelloClient.o
	${CXX} ${CFLAGS} -shared -Wl,-soname=HelloClient.node -Wl,--start-group ./hello/HelloClient.o ${GRPHQL} -lpthread ${NOTH_A} -Wl,--end-group -o $@

./today/sampleOne.o: ./today/sample.cpp
	${CXX} ${CFLAGS} -c $< -o $@

./today/sampleOne:
	${CXX} ${CFLAGS} ./today/sample.cpp -shared -Wl,-soname=sampleOne.node -Wl,--start-group ${GRPHQL} -lpthread ${NOTH_A} -Wl,--end-group -o $@

nothing.a: nothing.o
	ar crs nothing.a $<

nothing.o: nothing.c
	${CC} ${LDFLAGS} ${INC_NODE} ${DEFS} -c $< -o $@ 

HelloMock.h

#pragma once

#ifndef HELLOMOCK_H
#define HELLOMOCK_H

#include "HelloSchema.h"

#include <atomic>
#include <stack>

namespace graphql::hello
{
    class Hello;

    class Query
    {
        using helloLoader = std::function<std::vector<std::shared_ptr<Hello>>()>;
        public:
            explicit Query(helloLoader &&getHelloMsg);
            virtual service::FieldResult<std::optional<response::StringType>> getHelloMsg(service::FieldParams &&params) const final;
        private:
            // Lazy load the fields in each query
            void loadMsg(const std::shared_ptr<service::RequestState> &state) const;
            mutable helloLoader _getHelloMsg;
            mutable std::vector<std::shared_ptr<Hello>> _hello;
    };

    class Hello
    {
        public:
            explicit Hello(std::string&& greet);
            virtual service::FieldResult<std::optional<response::StringType>> getGreetMsg() final;
            virtual service::FieldResult<std::optional<response::StringType>> getForceError(
                service::FieldParams &&) const final
            {
                throw std::runtime_error(R"ex(this error was forced)ex");
            }

        private:
            std::string _greet;

        
    };

}

#endif // HELLOMOCK_H

HelloMock.cpp

#include "HelloMock.h"

#include <algorithm>
#include <iostream>

namespace graphql::hello
{

    Hello::Hello(std::string&& greet) : _greet(greet)
    {
    }
    service::FieldResult<std::optional<response::StringType>> Hello::getGreetMsg()
    {
        return _greet;
    }

    Query::Query(helloLoader&& getHelloMsg)
    {
    }
    void Query::loadMsg(const std::shared_ptr<service::RequestState> &state) const
    {
        if (_getHelloMsg)
        {
            _hello = _getHelloMsg();
            _getHelloMsg = nullptr;
        }
    }

    // std::shared_ptr<Hello> Query::findHelloMsg(
    //     const service::FieldParams &params, const response::IdType &id) const
    // {
    //     loadMsg(params.state);

    //     for (const auto &hello : _hello)
    //     {
    //         if (hello->id() == id)
    //         {
    //             return appointment;
    //         }
    //     }

    //     return nullptr;
    // }

} // namespace graphql::hello

hello.cpp

// #include <napi.h>
#include "HelloMock.h"

#include "graphqlservice/JSONResponse.h"
#include <cstdio>
#include <iostream>
#include <iterator>
#include <stdexcept>

using namespace graphql;

// Napi::String parseQuery(const Napi::CallbackInfo &info)
int main(int argc, char **argv)
{
    // Napi::Env env = info.Env();
    /* From HelloMock*/
    response::StringType helloKey;

    std::string fakeHelloKey("hello");
    helloKey.resize(fakeHelloKey.size());
    std::copy(fakeHelloKey.cbegin(), fakeHelloKey.cend(), helloKey.begin());
    
    std::cout << "Created the service..." << std::endl;

    auto query = std::make_shared<hello::Query>(
        [&fakeHelloKey]() -> std::vector<std::shared_ptr<hello::Hello>>
        {
            std::cout << "Called getHelloMsg..." << std::endl;
            return {std::make_shared<hello::Hello>("Hello World!")};
        }
    );
        
    auto service = std::make_shared<hello::Operations>(query);
    std::cout << "Created the service..." << std::endl;

    try
    {
        peg::ast query;
        // std::string qry = info[0].As<std::string>();
        // query = peg::parseString(std::move(qry));
        if (argc > 1)
        {
            query = peg::parseFile(argv[1]);
        }
        else
        {
            std::istream_iterator<char> start{std::cin >> std::noskipws}, end{};
            std::string input{start, end};

            query = peg::parseString(std::move(input));
        }
        if (!query.root)
        {
            std::cerr << "Unknown error!" << std::endl;
            std::cerr << std::endl;
            // return Napi::String::New(env, "1");
            return 1;
        }

        std::cout << "Executing query..." << std::endl;

        // std::stringstream out;
        // out << response::toJSON(service
        //                             ->resolve(nullptr,
        //                                       query,
        //                                       "",
        //                                       response::Value(response::Type::Map))
        //                             .get());
        // std::string res = out.str();
        // return Napi::String::New(env, res);
        std::cout << response::toJSON(service
                                          ->resolve(nullptr,
                                                    query,
                                                    ((argc > 2) ? argv[2] : ""),
                                                    response::Value(response::Type::Map))
                                          .get())
                  << std::endl;
    }
    catch (const std::runtime_error &ex)
    {
        std::cerr << ex.what() << std::endl;
        // return Napi::String::New(env, "1");
        return 1;
    }

    // return Napi::String::New(env, "0");
    return 0;
}

// Napi::Object Init(Napi::Env env, Napi::Object exports)
// {
//     exports.Set("parseQuery", Napi::Function::New(env, parseQuery));
//     return exports;
// }

// NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);

Error:

ar crs nothing.a nothing.o
g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -shared -Wl,-soname=HelloClient.node -Wl,--start-group ./hello/HelloClient.o -L/usr/local/lib/libgraphqlclient.a -L/usr/local/lib/libgraphqljson.a  -L/usr/local/lib/libgraphqlintrospection.a  -L/usr/local/lib/libgraphqlservice.a  -L/usr/local/lib/libgraphqlresponse.a  -L/usr/local/lib/libgraphqlpeg.a -lpthread nothing.a -Wl,--end-group -o hello/HelloClient.node
g++ -Os -O3 -fPIC -Ofast -std=gnu++17 ./hello/hello.cpp -shared -Wl,-soname=hello -Wl,--start-group -lpthread -L/usr/local/lib/libgraphqlclient.a -L/usr/local/lib/libgraphqljson.a  -L/usr/local/lib/libgraphqlintrospection.a  -L/usr/local/lib/libgraphqlservice.a  -L/usr/local/lib/libgraphqlresponse.a  -L/usr/local/lib/libgraphqlpeg.a -Wl,--end-group -o hello/hello
In file included from /usr/include/x86_64-linux-gnu/c++/10/bits/c++allocator.h:33,
                 from /usr/include/c++/10/bits/allocator.h:46,
                 from /usr/include/c++/10/memory:64,
                 from /usr/local/include/graphqlservice/GraphQLParse.h:21,
                 from /usr/local/include/graphqlservice/GraphQLService.h:21,
                 from /usr/local/include/graphqlservice/internal/Schema.h:9,
                 from ./hello/HelloSchema.h:11,
                 from ./hello/HelloMock.h:6,
                 from ./hello/hello.cpp:2:
/usr/include/c++/10/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = graphql::hello::Operations; _Args = {std::shared_ptr<graphql::hello::Query>&}; _Tp = graphql::hello::Operations]’:
/usr/include/c++/10/bits/alloc_traits.h:512:17:   required from ‘static void std::allocator_traits<std::allocator<_Tp1> >::construct(std::allocator_traits<std::allocator<_Tp1> >::allocator_type&, _Up*, _Args&& ...) [with _Up = graphql::hello::Operations; _Args = {std::shared_ptr<graphql::hello::Query>&}; _Tp = graphql::hello::Operations; std::allocator_traits<std::allocator<_Tp1> >::allocator_type = std::allocator<graphql::hello::Operations>]’
/usr/include/c++/10/bits/shared_ptr_base.h:551:39:   required from ‘std::_Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp>::_Sp_counted_ptr_inplace(_Alloc, _Args&& ...) [with _Args = {std::shared_ptr<graphql::hello::Query>&}; _Tp = graphql::hello::Operations; _Alloc = std::allocator<graphql::hello::Operations>; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10/bits/shared_ptr_base.h:682:16:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = graphql::hello::Operations; _Alloc = std::allocator<graphql::hello::Operations>; _Args = {std::shared_ptr<graphql::hello::Query>&}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = std::allocator<graphql::hello::Operations>; _Args = {std::shared_ptr<graphql::hello::Query>&}; _Tp = graphql::hello::Operations; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = std::allocator<graphql::hello::Operations>; _Args = {std::shared_ptr<graphql::hello::Query>&}; _Tp = graphql::hello::Operations]’
/usr/include/c++/10/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = graphql::hello::Operations; _Alloc = std::allocator<graphql::hello::Operations>; _Args = {std::shared_ptr<graphql::hello::Query>&}]’
/usr/include/c++/10/bits/shared_ptr.h:875:39:   required from ‘std::shared_ptr<_Tp> std::make_shared(_Args&& ...) [with _Tp = graphql::hello::Operations; _Args = {std::shared_ptr<graphql::hello::Query>&}]’
./hello/hello.cpp:33:61:   required from here
/usr/include/c++/10/ext/new_allocator.h:150:4: error: no matching function for call to ‘graphql::hello::Operations::Operations(std::shared_ptr<graphql::hello::Query>&)’
  150 |  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
      |    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from ./hello/HelloMock.h:6,
                 from ./hello/hello.cpp:2:
./hello/HelloSchema.h:52:11: note: candidate: ‘graphql::hello::Operations::Operations(std::shared_ptr<graphql::hello::object::Query>)’
   52 |  explicit Operations(std::shared_ptr<object::Query> query);
      |           ^~~~~~~~~~
./hello/HelloSchema.h:52:53: note:   no known conversion for argument 1 from ‘shared_ptr<graphql::hello::Query>’ to ‘shared_ptr<graphql::hello::object::Query>’
   52 |  explicit Operations(std::shared_ptr<object::Query> query);
      |                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
make: *** [makefile:89: hello/hello] Error 1

Using Schema

schema.hello.graphql

type Query {
    hello: String
}

query.hello.graphql

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

query {
    hello
}

Excpected output

{"data":{"hello":"Hello World!"}}

How to resolve that error message and how to get the final expected output?

Originally posted by Jeyaprakash (@YJPrakash) in #172 (comment)

Activity

  1. wravery commented on Dec 30, 2021

    @wravery
    ContributorAuthor

    I think the next error is because class Query does not inherit from object::Query, which is required in v3.x.

    You also need to override and match the signature of the virtual field accessors from object::Query in your implementation, but it looks like you've done that already.

  2. added
    question
    on Dec 30, 2021
  3. YJPrakash commented on Jan 3, 2022

    @YJPrakash

    After inheriting of class Query from object::Query is compiled without errors. Thank you Bill Avery (@wravery).

    Then I am enabling Napi.h following errors occur. If there any LDflags want to add for graphql::service.

    following libraries added for making hello.node -L/usr/local/lib/libgraphqlclient.a -L/usr/local/lib/libgraphqljson.a -L/usr/local/lib/libgraphqlintrospection.a -L/usr/local/lib/libgraphqlservice.a -L/usr/local/lib/libgraphqlresponse.a -L/usr/local/lib/libgraphqlpeg.a . Please take a look at it.

    hello.cpp

    #include <napi.h>
    #include "HelloMock.h"
    
    #include "graphqlservice/JSONResponse.h"
    #include <cstdio>
    #include <iostream>
    #include <iterator>
    #include <stdexcept>
    
    using namespace graphql;
    
    Napi::String parseQuery(const Napi::CallbackInfo &info)
    // int main(int argc, char **argv)
    {
        std::cout << "start hello 1" << std::endl;
        Napi::Env env = info.Env();
        /* From HelloMock*/
        response::StringType helloKey;
    
        std::string fakeHelloKey("hello");
        helloKey.resize(fakeHelloKey.size());
        std::copy(fakeHelloKey.cbegin(), fakeHelloKey.cend(), helloKey.begin());
        
        std::cout << "Created the service..." << std::endl;
    
        auto query = std::make_shared<hello::Query>(
            [&fakeHelloKey]() -> std::vector<std::shared_ptr<hello::Hello>>
            {
                std::cout << "Called getHelloMsg..." << std::endl;
                return {std::make_shared<hello::Hello>("Hello World!")};
            }
        );
            
        auto service = std::make_shared<hello::Operations>(query);
        std::cout << "Created the service..." << std::endl;
    
        try
        {
            peg::ast query;
            // std::string qry = info[0].As<std::string>();
            // query = peg::parseString(std::move(qry));
            // if (argc > 1)
            // {
            //     query = peg::parseFile(argv[1]);
            // }
            // else
            // {
                std::istream_iterator<char> start{std::cin >> std::noskipws}, end{};
                std::string input{start, end};
    
                query = peg::parseString(std::move(input));
            // }
            if (!query.root)
            {
                std::cerr << "Unknown error!" << std::endl;
                std::cerr << std::endl;
                return Napi::String::New(env, "1");
                // return 1;
            }
    
            std::cout << "Executing query..." << std::endl;
    
            std::stringstream out;
            out << response::toJSON(service
                                        ->resolve(nullptr,
                                                  query,
                                                  "",
                                                  response::Value(response::Type::Map))
                                        .get());
            std::string res = out.str();
            return Napi::String::New(env, res);
            // std::cout << response::toJSON(service
            //                                   ->resolve(nullptr,
            //                                             query,
            //                                             ((argc > 2) ? argv[2] : ""),
            //                                             response::Value(response::Type::Map))
            //                                   .get())
            //           << std::endl;
        }
        catch (const std::runtime_error &ex)
        {
            std::cerr << ex.what() << std::endl;
            return Napi::String::New(env, "1");
            // return 1;
        }
    
        return Napi::String::New(env, "0");
        // return 0;
    }
    
    Napi::Object Init(Napi::Env env, Napi::Object exports)
    {
        exports.Set("parseQuery", Napi::Function::New(env, parseQuery));
        return exports;
    }
    
    NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);
    

    Error:

    i) For commented line conversion is not working when enabling // std::string qry = info[0].As<std::string>(); error like typedef std::__cxx11::basic_string.
    ii) Node addon program compiled successfully after commented above line. after calling parseQuery function from nodejs error like Error: ./hello/hello.node: undefined symbol: _ZTIN7graphql7service6ObjectE

    Detailed error log:

    $ make 
    gcc -pthread -rdynamic -I/usr/include/node '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -c nothing.c -o nothing.o 
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -frtti -fexceptions -pthread -Wall -Wextra -Wno-unused-parameter -fno-omit-frame-pointer -I/usr/include/node-addon-api -I/usr/include/node -c hello/HelloSchema.cpp -o hello/HelloSchema.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -frtti -fexceptions -pthread -Wall -Wextra -Wno-unused-parameter -fno-omit-frame-pointer -I/usr/include/node-addon-api -I/usr/include/node -c hello/HelloMock.cpp -o hello/HelloMock.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 '-DNODE_GYP_MODULE_NAME=hello' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -frtti -fexceptions -pthread -Wall -Wextra -Wno-unused-parameter -fno-omit-frame-pointer -I/usr/include/node-addon-api -I/usr/include/node -c hello/hello.cpp -o hello/hello.o
    ar crs nothing.a nothing.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 ./hello/HelloSchema.o ./hello/HelloMock.o ./hello/hello.o -shared -Wl,-soname=hello.node -Wl,--start-group -lpthread -L/usr/local/lib/libgraphqlclient.a -L/usr/local/lib/libgraphqljson.a  -L/usr/local/lib/libgraphqlintrospection.a  -L/usr/local/lib/libgraphqlservice.a  -L/usr/local/lib/libgraphqlresponse.a  -L/usr/local/lib/libgraphqlpeg.a nothing.a -Wl,--end-group -o hello/hello.node
    
    
    $ cat query.hello.graphql | node -p "require('./hello/hello.node').parseQuery();"
    internal/modules/cjs/loader.js:1144
      return process.dlopen(module, path.toNamespacedPath(filename));
                     ^
    
    Error: ./hello/hello.node: undefined symbol: _ZTIN7graphql7service6ObjectE
        at Object.Module._extensions..node (internal/modules/cjs/loader.js:1144:18)
        at Module.load (internal/modules/cjs/loader.js:950:32)
        at Function.Module._load (internal/modules/cjs/loader.js:790:12)
        at Module.require (internal/modules/cjs/loader.js:974:19)
        at require (internal/modules/cjs/helpers.js:93:18)
        at [eval]:1:1
        at Script.runInThisContext (vm.js:134:12)
        at Object.runInThisContext (vm.js:310:38)
        at internal/process/execution.js:81:19
        at [eval]-wrapper:6:22 {
      code: 'ERR_DLOPEN_FAILED'
    }
    
  4. YJPrakash commented on Jan 3, 2022

    @YJPrakash
    $ nm ./hello/hello.node | grep _ZTIN7graphql7service6ObjectE
                     U _ZTIN7graphql7service6ObjectE
    
    
  5. wravery commented on Jan 3, 2022

    @wravery
    ContributorAuthor

    It looks like you're hitting errors specific to Node/Electron Native Modules now. Building a working native module is complicated and fragile, I've had to spend a lot of time going through V8 headers to unblock major version upgrades of Electron using undocumented -D defines. The safest way I know to do this is to use npm and cmake-js instead of trying to build with make, cmake-js takes care of some of the cross-platform and major version incompatibilities for you. Otherwise, you may need to switch to gyp and electron-rebuild, which I think are the officially supported build systems for Electron.

    All that aside, if you just want to pipe queries into an executable and get responses back, take a look at samples/today/sample.cpp. It works in interactive mode (stdin/stdout), or you can give it a file name for the query you want to execute.

  6. YJPrakash commented on Jan 4, 2022

    @YJPrakash

    Yes, correct I am using Node addon API. An error is like an undefined symbol of GraphQL service. So only I am posting the above comment. Today I tried without Napi.h, my source compiled successfully including CFLAGS -shared -fPIC. But, segmentation-fault occurs when running that program $./hello/hello query.hello.graphql. Without using above mentioned flags I am getting the following errors when compiling. What does it mean about these errors?

    g++ -std=gnu++17 -lgraphqlclient -lgraphqljson -lgraphqlintrospection -lgraphqlservice -lgraphqlresponse -lgraphqlpeg -c hello/HelloSchema.cpp -o hello/HelloSchema.o
    g++ -std=gnu++17 -lgraphqlclient -lgraphqljson -lgraphqlintrospection -lgraphqlservice -lgraphqlresponse -lgraphqlpeg -c hello/HelloMock.cpp -o hello/HelloMock.o
    g++ -std=gnu++17 -lgraphqlclient -lgraphqljson -lgraphqlintrospection -lgraphqlservice -lgraphqlresponse -lgraphqlpeg -c hello/hellosample.cpp -o hello/hellosample.o
    ar crs nothing.a nothing.o
    g++ -std=gnu++17 -pthread ./hello/hellosample.cpp -lpthread -lgraphqlclient -lgraphqljson -lgraphqlintrospection -lgraphqlservice -lgraphqlresponse -lgraphqlpeg -o hello/hellosample
    /usr/bin/ld: /tmp/ccFl0ZhB.o: in function `void __gnu_cxx::new_allocator<graphql::hello::Query>::construct<graphql::hello::Query, main::{lambda()#1}>(graphql::hello::Query*, main::{lambda()#1}&&)':
    hellosample.cpp:(.text+0x7fb): undefined reference to `graphql::hello::Query::Query(std::function<std::vector<std::shared_ptr<graphql::hello::Hello>, std::allocator<std::shared_ptr<graphql::hello::Hello> > > ()>&&)'
    /usr/bin/ld: /tmp/ccFl0ZhB.o: in function `void __gnu_cxx::new_allocator<graphql::hello::Hello>::construct<graphql::hello::Hello, char const (&) [13]>(graphql::hello::Hello*, char const (&) [13])':
    hellosample.cpp:(.text._ZN9__gnu_cxx13new_allocatorIN7graphql5hello5HelloEE9constructIS3_JRA13_KcEEEvPT_DpOT0_[_ZN9__gnu_cxx13new_allocatorIN7graphql5hello5HelloEE9constructIS3_JRA13_KcEEEvPT_DpOT0_]+0x79): undefined reference to `graphql::hello::Hello::Hello(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&)'
    /usr/bin/ld: /tmp/ccFl0ZhB.o: in function `void __gnu_cxx::new_allocator<graphql::hello::Operations>::construct<graphql::hello::Operations, std::shared_ptr<graphql::hello::Query>&>(graphql::hello::Operations*, std::shared_ptr<graphql::hello::Query>&)':
    hellosample.cpp:(.text._ZN9__gnu_cxx13new_allocatorIN7graphql5hello10OperationsEE9constructIS3_JRSt10shared_ptrINS2_5QueryEEEEEvPT_DpOT0_[_ZN9__gnu_cxx13new_allocatorIN7graphql5hello10OperationsEE9constructIS3_JRSt10shared_ptrINS2_5QueryEEEEEvPT_DpOT0_]+0x69): undefined reference to `graphql::hello::Operations::Operations(std::shared_ptr<graphql::hello::object::Query>)'
    /usr/bin/ld: /tmp/ccFl0ZhB.o: in function `graphql::hello::Hello::~Hello()':
    hellosample.cpp:(.text._ZN7graphql5hello5HelloD2Ev[_ZN7graphql5hello5HelloD5Ev]+0x13): undefined reference to `vtable for graphql::hello::Hello'
    collect2: error: ld returned 1 exit status
    make: *** [makefile:107: hello/hellosample] Error 1
    
    

    Please help me. In my project already we tried node-gyp build tool. All other(without node-addon) CPP files were compiled using the make utility. so we found a way to write the Node addon with make utility manually one make process. that's why I am using that above-mentioned make utility.

  7. YJPrakash commented on Jan 5, 2022

    @YJPrakash
    $ make 
    gcc -pthread -rdynamic -I/usr/include/node '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -c nothing.c -o nothing.o 
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/GraphQLService.cpp -o src/GraphQLService.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/Schema.cpp -o src/Schema.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/Validation.cpp -o src/Validation.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/Base64.cpp -o src/Base64.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/GraphQLResponse.cpp -o src/GraphQLResponse.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/SyntaxTree.cpp -o src/SyntaxTree.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/JSONResponse.cpp -o src/JSONResponse.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/Introspection.cpp -o src/Introspection.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/IntrospectionSchema.cpp -o src/IntrospectionSchema.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -I./include -c src/GraphQLClient.cpp -o src/GraphQLClient.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -c hello/HelloSchema.cpp -o hello/HelloSchema.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -c hello/HelloMock.cpp -o hello/HelloMock.o
    ar qc libhellographql.a  ./hello/HelloMock.o
    ranlib libhellographql.a
    ar qc libhelloschema.a  ./hello/HelloSchema.o
    ranlib libhelloschema.a
    ar qc libgraphqlclient.a  ./src/GraphQLClient.o
    ranlib libgraphqlclient.a
    ar qc libgraphqljson.a  ./src/JSONResponse.o
    ranlib libgraphqljson.a
    ar qc libgraphqlintrospection.a ./src/Introspection.o ./src/IntrospectionSchema.o
    ranlib libgraphqlintrospection.a
    ar qc libgraphqlservice.a ./src/GraphQLService.o ./src/Schema.o ./src/Validation.o
    ranlib libgraphqlservice.a
    ar qc libgraphqlresponse.a  ./src/Base64.o ./src/GraphQLResponse.o
    ranlib libgraphqlresponse.a
    ar qc libgraphqlpeg.a ./src/SyntaxTree.o
    ranlib libgraphqlpeg.a
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 '-DNODE_GYP_MODULE_NAME=hello' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-D__STDC_FORMAT_MACROS' '-DNAPI_DISABLE_CPP_EXCEPTIONS' '-DBUILDING_NODE_EXTENSION' -frtti -fexceptions -pthread -Wall -Wextra -Wno-unused-parameter -fno-omit-frame-pointer -I/usr/include/node-addon-api -I/usr/include/node -c hello/hello.cpp -o hello/hello.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -c hello/hellosample.cpp -o hello/hellosample.o
    ar crs nothing.a nothing.o
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 -shared -Wl,-soname=hello.node -Wl,--start-group ./hello/hello.o libhellographql.a libhelloschema.a libgraphqlclient.a libgraphqljson.a libgraphqlintrospection.a libgraphqlservice.a libgraphqlresponse.a libgraphqlpeg.a -lpthread nothing.a -Wl,--end-group -o hello/hello.node
    g++ -Os -O3 -fPIC -Ofast -std=gnu++17 ./hello/hellosample.o -o hello/hellosample.node libhellographql.a libhelloschema.a -lgraphqlclient -lgraphqljson -lgraphqlintrospection -lgraphqlservice -lgraphqlresponse -lgraphqlpeg -lpthread 
    
    $ ./hello/hellosample.node query.hello.graphql 
    1
    Creating the query service...
    Created the service...
    Executing query...
    {"data":{"hello":null},"errors":[{"message":"Field error name: hello unknown error: Query::getHello is not implemented","locations":[{"line":5,"column":5}],"path":["hello"]}]}
    

    For Node addon fix:

    $ nm ./hello/hello.node | grep _ZTIN7graphql7service6ObjectE
                     U _ZTIN7graphql7service6ObjectE
    

    Node addon using libgraphqlservice.a. That was recompiled with -fPIC flags.
    Finally, I am found a way to write node addon with Napi.h.

    why I am getting the error "errors":[{"message":"Field error name: hello unknown error: Query::getHello is not implemented" throw from that executable?. But I am implementing that getHello function in HelloMock.cpp.
    Please review my code.

    HelloMock.h

    #pragma once
    
    #ifndef HELLOMOCK_H
    #define HELLOMOCK_H
    
    #include "HelloSchema.h"
    
    #include <atomic>
    #include <stack>
    
    namespace graphql::hello
    {
        struct RequestState : service::RequestState
        {
            RequestState(size_t id)
                : requestId(id)
            {
            }
    
            const size_t requestId;
    
            size_t greetsRequestId = 0;
    
            size_t greetsCount = 0;
        };
    
        class Hello;
    
        class Query : public object::Query
        {
            using helloLoader = std::function<std::vector<std::shared_ptr<Hello>>()>;
    
            public:
                explicit Query(helloLoader&& getHello);
                virtual service::FieldResult<std::optional<response::StringType>> getHello(const service::FieldParams&& params) const final;
    
            private:
                std::shared_ptr<Hello> findHello(const service::FieldParams &params) const;
                // Lazy load the fields in each query
                void loadHello(const std::shared_ptr<service::RequestState> &state) const;
                mutable helloLoader _getHello;
                mutable std::vector<std::shared_ptr<Hello>> _hello;
        };
    
        class Hello
        {
            public:
                explicit Hello(std::string&& greet);
                virtual service::FieldResult<std::optional<response::StringType>> getHello() final;
                virtual service::FieldResult<std::optional<response::StringType>> getForceError(
                    service::FieldParams &&) const final
                {
                    throw std::runtime_error(R"ex(this error was forced)ex");
                }
    
            private:
                std::string _greet;
    
            
        };
    
    }
    
    #endif // HELLOMOCK_H
    
    

    HelloMock.cpp

    #include "HelloMock.h"
    
    #include <algorithm>
    #include <iostream>
    
    namespace graphql::hello
    {
    
        Hello::Hello(std::string&& greet) : _greet(greet)
        {
        }
        service::FieldResult<std::optional<response::StringType>> Hello::getHello()
        {
            return _greet;
        }
    
        Query::Query(helloLoader&& getHello) 
        : _getHello(std::move(getHello))
        {
        }
    
        service::FieldResult<std::optional<response::StringType>> hello::Query::getHello(const service::FieldParams&& params) const
        {
            std::shared_ptr<Hello>  _hello = findHello(params);
            return _hello->getHello();
            // return _getHello();
        }
        
        void Query::loadHello(const std::shared_ptr<service::RequestState> &state) const
        {
            if (_getHello)
            {
                _hello = _getHello();
                _getHello = nullptr;
            }
        }
    
        std::shared_ptr<Hello> Query::findHello(const service::FieldParams &params) const
        {
            loadHello(params.state);
            // if(_hello != nullptr) return _hello;
            for (const auto &hello : _hello)
            {
                if (hello)
                {
                    return hello;
                }
            }
    
    
            return nullptr;
        }
    
    } // namespace graphql::hello
    
    
    

    hellosample.cpp

    #include "HelloMock.h"
    
    #include "graphqlservice/JSONResponse.h"
    #include <cstdio>
    #include <iostream>
    #include <iterator>
    #include <stdexcept>
    
    using namespace graphql;
    
    int main(int argc, char **argv)
    {
        std::cerr << "1" << std::endl;
        /* From HelloMock*/
        response::StringType helloKey;
    
        std::string fakeHelloKey("hello");
        helloKey.resize(fakeHelloKey.size());
        std::copy(fakeHelloKey.cbegin(), fakeHelloKey.cend(), helloKey.begin());
        
        std::cerr << "Creating the query service..." << std::endl;
    
        auto query = std::make_shared<hello::Query>(
            [&fakeHelloKey]() -> std::vector<std::shared_ptr<hello::Hello>>
            {
                std::cout << "Called getHello..." << std::endl;
                return {std::make_shared<hello::Hello>("Hello World!")};
            });
    
        auto service = std::make_shared<hello::Operations>(query);
        std::cout << "Created the service..." << std::endl;
    
        try
        {
            peg::ast query;
            if (argc > 1)
            {
                query = peg::parseFile(argv[1]);
            }
            else
            {
                std::istream_iterator<char> start{std::cin >> std::noskipws}, end{};
                std::string input{start, end};
    
                query = peg::parseString(std::move(input));
            }
            if (!query.root)
            {
                std::cerr << "Unknown error!" << std::endl;
                std::cerr << std::endl;
                return 1;
            }
    
            std::cout << "Executing query..." << std::endl;
    
            std::cout << response::toJSON(service
                                              ->resolve(nullptr,
                                                        query,
                                                        ((argc > 2) ? argv[2] : ""),
                                                        response::Value(response::Type::Map))
                                              .get())
                      << std::endl;
        }
        catch (const std::runtime_error &ex)
        {
            std::cerr << ex.what() << std::endl;
            return 1;
        }
    
        return 0;
    }
    
    

    https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable#:~:text=In%20summary%2C%20there%20are%20three%20key%20causes%20of,insufficient%20to%20cause%20the%20error%20on%20their%20own.

    It may helpful for implementing getHello function. I will take some time to read about it. Thank you for your help. Bill Avery (@wravery)

  8. wravery commented on Jan 5, 2022

    @wravery
    ContributorAuthor

    why I am getting the error "errors":[{"message":"Field error name: hello unknown error: Query::getHello is not implemented" throw from that executable?. But I am implementing that getHello function in HelloMock.cpp. Please review my code.

    HelloMock.h

        class Query : public object::Query
        {
            using helloLoader = std::function<std::vector<std::shared_ptr<Hello>>()>;
    
            public:
                explicit Query(helloLoader&& getHello);
                virtual service::FieldResult<std::optional<response::StringType>> getHello(const service::FieldParams&& params) const final;
    
            private:
                std::shared_ptr<Hello> findHello(const service::FieldParams &params) const;
                // Lazy load the fields in each query
                void loadHello(const std::shared_ptr<service::RequestState> &state) const;
                mutable helloLoader _getHello;
                mutable std::vector<std::shared_ptr<Hello>> _hello;
        };
    

    The getHello method should be declared with the final keyword and without the virtual keyword, so the compiler can tell you if you didn't override it properly. In this case, I think it will fail to override the stub because the signature doesn't match, you're taking a const service::FieldParams&& instead of service::FieldParams&&. I can't think of a reason why a move/r-value reference would be const, so you should probably just remove that.

    The loader function is definitely too complicated for this purpose, TodayMock uses this for testing purposes (it's a test mock). A more realistic and better structured example is the learn sample based on the https://graphql.org tutorial, I'd suggest starting from there.

        class Hello
        {
            public:
                explicit Hello(std::string&& greet);
                virtual service::FieldResult<std::optional<response::StringType>> getHello() final;
                virtual service::FieldResult<std::optional<response::StringType>> getForceError(
                    service::FieldParams &&) const final
                {
                    throw std::runtime_error(R"ex(this error was forced)ex");
                }
    
            private:
                std::string _greet;
    
            
        };
    

    This class Hello doesn't inherit from anything, so it should not have any virtual or final methods. That may be confusing gcc and contributing to the undefined reference to `vtable error.

    https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable#:~:text=In%20summary%2C%20there%20are%20three%20key%20causes%20of,insufficient%20to%20cause%20the%20error%20on%20their%20own.

    It may helpful for implementing getHello function. I will take some time to read about it. Thank you for your help. Bill Avery (@wravery)

    I should have clarified, that's a discussion specifically about the undefined reference to `vtable error. It has lots of great troubleshooting information.

  9. wravery commented on Jan 21, 2022

    @wravery
    ContributorAuthor

    Closing since I haven't heard anything for a couple of weeks. If you're still stuck, feel free to add more comments or open a new issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions