Closed simonw closed 2 years ago
from datasette_graphql import hookimpl
def extra_fields(datasette):
return [
("hello", graphene.String(), lambda root, info: "Hello world"),
]
Returns a name, a field type and a resolve function - these are then added to the query at the root of the Schema.
Would use the same optional async def inner()
pattern as other hooks.
Open question: what if the name from a plugin collides with the name of a SQLite table?
Could solve that by automatically renaming the GraphQL field for that table.
The Postgraphile project handles many of the same types of issues, you may want to look there for inspiration. It has awesome plugins
I proved in https://github.com/simonw/datasette-low-disk-space-hook that you can add new plugin hooks as part of another plugin, see also this TIL: https://til.simonwillison.net/datasette/register-new-plugin-hooks
I'm going to experiment with this hook using https://datasette.io/plugins/datasette-packages since it's a really simple plugin (much simpler than datasette-ripgrep
).
Here's the hookspec:
from pluggy import HookspecMarker
hookspec = HookspecMarker("datasette")
@hookspec
def graphql_extra_fields(datasette):
"A list of (name, field_type) tuples to include in the GraphQL schema"
And an example plugin implementation:
@hookimpl
def graphql_extra_fields():
class Package(graphene.ObjectType):
"An installed package"
name = graphene.String()
version = graphene.String()
return [
(
"packages",
graphene.Field(
graphene.List(Package),
description="List of installed packages",
resolver=lambda root, info: [
{"name": d.project_name, "version": d.version}
for d in sorted(
pkg_resources.working_set, key=lambda d: d.project_name.lower()
)
])
),
]
Originally posted by @simonw in https://github.com/simonw/datasette-ripgrep/issues/18#issuecomment-737847561