Is there a JavaScript equivalent of Java’s
class.getName()
?
But here are various hacks that all fall down in one way or another:
Here is a hack that will do what you need — be aware that it modifies the Object’s prototype, something people frown upon (usually for good reason)
Object.prototype.getName = function() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((this).constructor.toString()); return (results && results.length > 1) ? results[1] : "";
};
Now, all of your objects will have the function, getName()
, that will return the name of the constructor as a string. I have tested this in FF3
and IE7
, I can’t speak for other implementations.
@Resolver()
export class FooResolver { @Query(() => String) sayHello(): string { return 'Hello World!'; }
}
- Similar question
- Related Query
- More Query from same tag
- Stuck on an issue?
- Issue Description
- Discription
- Intended outcome
- Actual outcome
- How to reproduce the issue
- Issue Analytics
- Top Results From Across the Web
- Tags:
- graphql
- apollo
- People also ask
- 2 Answers
- Using the instanceof operator.
- Will not work cross-frame and cross-window
- What is the motivation / use case for changing the behavior?
- Current behavior
- Caveats for all.
- NOTE:
- Environment
- Minimal reproduction of the problem with instructions
- I’m submitting a…
- Others
- Using Object. prototype. toString
- 2 ответа
- Expected behavior
- Using the constructor property.
- Caveats
- Using the name property of the constructor property.
- Does not work AT ALL in many cases
- Does NOT work in <IE9
Similar question
In my case, I forgot to add my resolver file on the providers array on my Module.
After running it again, everything went fine and schema.gql file was created at the same time.
Just make sure to add both Service and Resolver to your providers. 😀
In my case I had nfts.module.ts
which is registered in app.module.ts
but it was not configured properly. I had to pass providers
@Module({ providers: [NftsResolver, NftsService] })
export class NftsModule {}
This answer is not a direct answer to the question.
But if you are facing the described problem and the answers don’t help, recheck if you are using the correct imports:
// Correct
import { Resolver, Query } from '@nestjs/graphql';
// Incorrect in NestJS
import { Resolver, Query } from 'type-graphql';
Also ensure the Resolver is added in the module providers
@Module({ imports: [ GraphQLModule.forRoot({ installSubscriptionHandlers: true, autoSchemaFile: true, }), ], controllers: [], providers: [FooResolver], //< This
})
export class FooModule {}
Related Query
More Query from same tag
Stuck on an issue?
Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.
And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.
Issue Description
Discription
I am trying to stitch two schemas that one of them only contains a Mutation type using the latestgraphql-tools
v3.0.0. The error will disappear if any Query type contains more than one field is added to the single-mutation schema.
Since the error is not the same as #659 and that issue has been a while before the v3.0.0 was out, I open this issue. Please close this if you think this is duplicate.
Related issue: #659
Related PR: #746
Intended outcome
Querying Mutation test field should return a string result.
Actual outcome
“Query root type must be provided.” error is returned.
How to reproduce the issue
type Query { hello: String!
}
type Mutation { test: String!
}
mutation { test
}
{ "errors": [ { "message": "Query root type must be provided.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "test" ] } ], "data": null
}
Issue Analytics
- Created 5 years ago
- 32 (3 by maintainers)
Top Results From Across the Web
Apollo GraphQL Error: Query root type must be provided
Apollo Federation subgraph specification
Schema Stitching — Hot Chocolate v10
Type Merging – GraphQL Tools
Я использую NestJS, TypeORM и GraphQL для моего внутреннего API. Я получаю следующую ошибку:
GraphQLError [Object]: Query root type must be provided. at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19) at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13) at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3) at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62) at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59 at new Promise (<anonymous>) at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10) at GraphQLSchemaFactory.<anonymous> (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52) at Generator.next (<anonymous>) at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75
Вот как выглядит моя файловая структура и код:
Кто-нибудь может мне помочь. Мое репо: https://github.com/wise-introvert/nestjs-graphql -api.git
Tags:
graphql
apollo
I have an Angular/Apollo GraphQL implementation generating typescript code based on GraphQl endpoint which is surfacing a schema. I can hit the endpoint via Postman with a query and results are returned. However, when I run «graphql-codegen —config codegen.yml» via npm I get this error:
«Error: Query root type must be provided»
The server side is .Net Core implementation using GraphQL ASPNetCore. I have 4 different queries defined and each one works via graphiql.
Any ideas on why query root type is now being returned as null?
People also ask
What is root query in GraphQL?
Root fields & resolvers At the top level of every GraphQL server is a type that represents all of the possible entry points into the GraphQL API, it’s often called the Root type or the Query type. In this example, our Query type provides a field called human which accepts the argument id .
What is query type in GraphQL?
A GraphQL query is used to read or fetch values while a mutation is used to write or post values. In either case, the operation is a simple string that a GraphQL server can parse and respond to with data in a specific format. The popular response format that is usually used for mobile and web applications is JSON.
What is the return type of GraphQL?
GraphQL schema says that this object should return 4 properties: id , date , specialist , client .
What is ID type in GraphQL?
ID : The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.
2 Answers
export class FooResolver { @Query(() => String) sayHello(): string { return 'Hello World!'; }
}
This error throws when your schema stiching/definitions are incorrect. Please check the check your root schema definitions
GraphQLError [Object]: Query root type must be provided. at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19) at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13) at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3) at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62) at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59 at new Promise (<anonymous>) at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10) at GraphQLSchemaFactory.<anonymous> (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52) at Generator.next (<anonymous>) at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75
This is what my file structure and code looks like:
Can someone please help me. My repo: https://github.com/wise-introvert/nestjs-graphql-api.git
What is root query in GraphQL?
Root fields & resolvers At the top level of every GraphQL server is a type that represents all of the possible entry points into the GraphQL API, it’s often called the Root type or the Query type. In this example, our Query type provides a field called human which accepts the argument id .
How do you define schema in GraphQL?
A GraphQL schema is a description of the data clients can request from a GraphQL API. It also defines the queries and mutation functions that the client can use to read and write data from the GraphQL server. In other words, you specify your client or application UI data requirements in your GraphQL schema.
@Resolver()
export class FooResolver { @Query(() => String) sayHello(): string { return 'Hello World!'; }
}
Using the instanceof operator.
The instanceof
operator is a clean way of testing object
type as well, but has its own potential issues, just like the constructor
property.
var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
But instanceof
fails to work for literal values (because literals are not Objects
)
3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
The literals need to be wrapped in an Object
in order for instanceof
to work, for example
new Number(3) instanceof Number // true
The .constructor
check works fine for literals because the .
method invocation implicitly wraps the literals in their respective object type
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
Why two dots for the 3? Because Javascript interprets the first dot as a decimal point 😉
Will not work cross-frame and cross-window
instanceof
also will not work across different windows, for the same reason as the constructor
property check.
What is the motivation / use case for changing the behavior?
Smooth GraphQL integration
Current behavior
Error out when starting the dev server. See: https://codesandbox.io/s/gifted-black-rtzun?file=/package.json
[20:42:44] Found 0 errors. Watching for file changes.
Debugger listening on ws://127.0.0.1:9229/9b8e820d-ff88-4e22-a694-e48e5b1aa6af
For help, see: https://nodejs.org/en/docs/inspector
[Nest] 60446 - 04/27/2020, 20:42:45 [NestFactory] Starting Nest application...
[Nest] 60446 - 04/27/2020, 20:42:45 [InstanceLoader] AppModule dependencies initialized +13ms
[Nest] 60446 - 04/27/2020, 20:42:45 [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +1ms
[Nest] 60446 - 04/27/2020, 20:42:45 [InstanceLoader] GraphQLModule dependencies initialized +0ms
[Nest] 60446 - 04/27/2020, 20:42:45 [RoutesResolver] AppController {}: +3ms
[Nest] 60446 - 04/27/2020, 20:42:45 [RouterExplorer] Mapped {, GET} route +2ms
[ GraphQLError [Object]: Query root type must be provided. at SchemaValidationContext.reportError (dev/nest-project/node_modules/graphql/type/validate.js:88:19) at validateRootTypes (dev/nest-project/node_modules/graphql/type/validate.js:107:13) at validateSchema (/dev/nest-project/node_modules/graphql/type/validate.js:52:3) at graphqlImpl (dev/nest-project/node_modules/graphql/graphql.js:79:62) at /dev/nest-project/node_modules/graphql/graphql.js:28:59 at new Promise (<anonymous>) at Object.graphql (dev/nest-project/node_modules/graphql/graphql.js:26:10) at GraphQLSchemaFactory.<anonymous> (/dev/nest-project/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:48:52) at Generator.next (<anonymous>) at /dev/nest-project/node_modules/tslib/tslib.js:113:75 { message: 'Query root type must be provided.' }
]
(node:60446) UnhandledPromiseRejectionWarning: Error: Schema generation error (code-first approach) at GraphQLSchemaFactory.<anonymous> (/dev/nest-project/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:50:27) at Generator.next (<anonymous>) at fulfilled (dev/nest-project/node_modules/tslib/tslib.js:110:62) at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:60446) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:60446) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Caveats for all.
All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:
// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don’t assume anything, if you don’t understand exactly what you are after, you may end up with code breaking where you don’t expect it to because of a lack of grokking the subtleties.
NOTE:
Discussion of the typeof
operator may appear to be a glaring omission, but it really isn’t useful in helping to identify whether an object
is a given type, since it is very simplistic. Understanding where typeof
is useful is important, but I don’t currently feel that it is terribly relevant to this discussion. My mind is open to change though. 🙂
For a specific case when you need all query params:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
You can use URLSearchParams which is simple and has decent (but not complete) browser support.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
You don’t need jQuery for that purpose. You can use just some pure JavaScript:
function getParameterByName(name, url = window.location.href) { name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
NOTE: If a parameter is present several times (?foo=lorem&foo=ipsum
), you will get the first value (lorem
). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add ‘i’ modifier to RegExp
This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled «URLSearchParams» below.
Environment
[System Information]
OS Version : macOS Catalina
NodeJS Version : v12.16.1
YARN Version : 1.22.4
[Nest CLI]
Nest CLI Version : 7.1.4
[Nest Platform Information]
platform-express version : 7.0.0
graphql version : 7.3.4
common version : 7.0.0
core version : 7.0.0
other
Tested in a node:12 docker container as well. Same result.
Minimal reproduction of the problem with instructions
- Install nestjs via cli
- Install depdendencies for graphql
- Add simple module, model, resolver …
- Include the module to the app.module
- Run
yarn start:dev
I’m submitting a…
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Others
I’ve already burned down the node_module, dist and yarn.lock to see if it was a corrupt package installed by the CLI, but no change.
Using Object. prototype. toString
It turns out, as this post details, you can use Object.prototype.toString
— the low level and generic implementation of toString
— to get the type for all built-in types
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
One could write a short helper function such as
function type(obj){ return Object.prototype.toString.call(obj).slice(8, -1);
}
to remove the cruft and get at just the type name
type('abc') // String
2 ответа
@Resolver()
export class FooResolver { @Query(() => String) sayHello(): string { return 'Hello World!'; }
}
28 Сен 2020 в 16:24
Убедитесь, что Resolver также добавлен в поставщики модулей
@Module({ imports: [ GraphQLModule.forRoot({ installSubscriptionHandlers: true, autoSchemaFile: true, }), ], controllers: [], providers: [FooResolver], //< This
})
export class FooModule {}
4 Дек 2020 в 13:19
Expected behavior
It doesn’t crash when a resolver is supposed to be present
Using the constructor property.
Every object
has a value for its constructor
property, but depending on how that object
was constructed as well as what you want to do with that value, it may or may not be useful.
Generally speaking, you can use the constructor
property to test the type of the object like so:
var myArray = [1,2,3];
(myArray.constructor == Array); // true
Caveats
Will not work AT ALL in many cases
This pattern, though broken, is quite common:
function Thingy() {
}
Thingy.prototype = { method1: function() { }, method2: function() { }
};
Objects
constructed via new Thingy
will have a constructor
property that points to Object
, not Thingy
. So we fall right at the outset; you simply cannot trust constructor
in a codebase that you don’t control.
An example where it isn’t as obvious is using multiple inheritance:
function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
Things now don’t work as you might expect them to:
var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
So, you might get unexpected results if the object
your testing has a different object
set as its prototype
. There are ways around this outside the scope of this discussion.
There are other uses for the constructor
property, some of them interesting, others not so much; for now we will not delve into those uses since it isn’t relevant to this discussion.
Will not work cross-frame and cross-window
Using .constructor
for type checking will break when you want to check the type of objects coming from different window
objects, say that of an iframe or a popup window. This is because there’s a different version of each core type constructor
in each `window’, i.e.
iframe.contentWindow.Array === Array // false
Using the name property of the constructor property.
Does not work AT ALL in many cases
Again, see above; it’s quite common for constructor
to be utterly and completely wrong and useless.
Does NOT work in <IE9
Using myObjectInstance.constructor.name
will give you a string containing the name of the constructor
function used, but is subject to the caveats about the constructor
property that were mentioned earlier.
For IE9 and above, you can monkey-patch in support:
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get: function() { var funcNameRegex = /function\s+([^\s(]+)\s*\(/; var results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1] : ""; }, set: function(value) {} });
}
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get: function() { var funcNameRegex = /function\s([^(]{1,})\(/; var results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1].trim() : ""; }, set: function(value) {} });
}