Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added ability to override federation version on export schema command #3697

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Release type: patch

Added option for the export_schema command to override the output federation version.
ussage example: strawberry export-schema --federation-version=2.5
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved

This change ONLY effect "strawberry export-schema" command and is fully backword-compatible without any logic change.
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved

Warning: Please use with caution!!

If the schema define directives that are not supported by the specified version (in the override parameter) the schema
will still generate the output useing the value from the override, and may break at runtime.
iotflowadmin marked this conversation as resolved.
Show resolved Hide resolved
12 changes: 12 additions & 0 deletions docs/guides/schema-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,15 @@ Alternatively, the `--output` option can be used:
```bash
strawberry export-schema package.module:schema --output schema.graphql
```

You can override the output directive to have specific federation schema (e.g:
schema @link(url: "https://specs.apollo.dev/federation/v2.5"):

```bash
strawberry export-schema package.module:schema --federation-version=2.5 --output schema.graphql
```

> [!WARNING] \
> If the schema define directives that are not supported by the specified
> version (in the override parameter) the schema will still generate the output
> useing the value from the override, and may break at runtime.
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved
12 changes: 12 additions & 0 deletions strawberry/cli/commands/export_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,19 @@ def export_schema(
"-o",
help="File to save the exported schema. If not provided, prints to console.",
),
federation_version: Path = typer.Option(
None,
"--federation-version",
"-e",
help=(
"Override the output federation schema version. please use with care!"
"schema may brake if it have directives that are not supported by the defined federation version."
iotflowadmin marked this conversation as resolved.
Show resolved Hide resolved
"(for directive version compatibility please see: https://www.apollographql.com/docs/graphos/reference/federation/directives)"
),
),
) -> None:
if federation_version:
app.__setattr__("federation_version_override", federation_version)
schema_symbol = load_schema(schema, app_dir)

schema_text = print_schema(schema_symbol)
Expand Down
20 changes: 20 additions & 0 deletions strawberry/federation/schema_directives.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import typing
from dataclasses import dataclass
from typing import ClassVar, List, Optional

from strawberry import directive_field
from strawberry.cli import app
from strawberry.schema_directive import Location, schema_directive
from strawberry.types.unset import UNSET

Expand All @@ -11,12 +13,30 @@
LinkPurpose,
)

FEDERATION_VERSION_BASE_URL = "https://specs.apollo.dev/federation/v"


@dataclass
class ImportedFrom:
name: str
url: str = "https://specs.apollo.dev/federation/v2.7"

def __init__(self, **kwargs: typing.Dict[str, typing.Any]) -> None:
if hasattr(self, "__dataclass_fields__"):
args = self.__dataclass_fields__
for key, value in kwargs.items():
if key in args and type(value) is args.get(key).type:
self.__setattr__(key, value)
if (
hasattr(app, "federation_version_override")
and type(value) is str
and str(value).startswith("https://specs.apollo.dev/federation/")
):
self.__setattr__(
key,
f"{FEDERATION_VERSION_BASE_URL}{app.federation_version_override!s}",
)


class FederationDirective:
imported_from: ClassVar[ImportedFrom]
Expand Down
41 changes: 41 additions & 0 deletions tests/cli/test_export_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,47 @@ def test_schema_export(cli_app: Typer, cli_runner: CliRunner):
)
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved


def test_schema_export_with_federation_version_override(
cli_app: Typer, cli_runner: CliRunner
):
selector = "tests.fixtures.sample_package.sample_module_federated:schema"
result = cli_runner.invoke(
cli_app, ["export-schema", selector, "--federation-version=2.5"]
)
assert result.exit_code == 0
assert result.stdout == (
'schema @link(url: "https://specs.apollo.dev/federation/v2.5", import: '
'["@key"]) {\n'
" query: Query\n"
"}\n"
"\n"
'type Organization @key(fields: "id") {\n'
" id: ID!\n"
" name: String!\n"
" owner: User!\n"
"}\n"
"\n"
"type Query {\n"
" _entities(representations: [_Any!]!): [_Entity]!\n"
" _service: _Service!\n"
" organizations: [Organization!]!\n"
" organization(id: ID!): Organization\n"
"}\n"
"\n"
'type User @key(fields: "id", resolvable: false) {\n'
" id: ID!\n"
"}\n"
"\n"
"scalar _Any\n"
"\n"
"union _Entity = Organization | User\n"
"\n"
"type _Service {\n"
" sdl: String!\n"
"}\n"
)


def test_default_schema_symbol_name(cli_app: Typer, cli_runner: CliRunner):
selector = "tests.fixtures.sample_package.sample_module"
result = cli_runner.invoke(cli_app, ["export-schema", selector])
Expand Down
65 changes: 65 additions & 0 deletions tests/fixtures/sample_package/sample_module_federated.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import typing

import strawberry
from strawberry.federation.schema_directives import Key


@strawberry.federation.type(directives=[Key(fields="id", resolvable=False)])
class User:
id: strawberry.ID


async def get_user(root: "Organization", info: strawberry.Info) -> User:
return User(id=root._owner)


@strawberry.federation.type(keys=["id"])
class Organization:
id: strawberry.ID
name: str
_owner: strawberry.Private[User]
owner: User = strawberry.field(resolver=get_user)

@classmethod
async def resolve_reference(
cls, id: strawberry.ID
) -> typing.Optional["Organization"]:
return await get_organization_by_id(id=id)


async def get_organizations():
return [
Organization(
id=strawberry.ID("org1"),
name="iotflow",
_owner="abcdert1",
),
Organization(
id=strawberry.ID("org2"),
name="ibrag",
_owner="abdfr2",
),
]


async def get_organization_by_id(id: strawberry.ID) -> typing.Optional[Organization]:
for organization in await get_organizations():
if organization.id == id:
return organization
return None


@strawberry.type
class Query:
organizations: typing.List[Organization] = strawberry.field(
resolver=get_organizations
)

@strawberry.field
async def organization(self, id: strawberry.ID) -> typing.Optional[Organization]:
return await get_organization_by_id(id)


schema = strawberry.federation.Schema(
query=Query, types=[Organization, User], enable_federation_2=True
)
Loading