grafbase_hooks/hooks/authorization/
node_pre_execution_arguments.rs

1/// Arguments passed to the `authorize_node_pre_execution` hook.
2pub struct NodePreExecutionArguments {
3    definition: crate::wit::NodeDefinition,
4    metadata: String,
5}
6
7impl NodePreExecutionArguments {
8    pub(crate) fn new(definition: crate::wit::NodeDefinition, metadata: String) -> Self {
9        Self { definition, metadata }
10    }
11
12    /// The name of the node type.
13    ///
14    /// For the following GraphQL schema:
15    ///
16    /// ```graphql
17    /// type User @authorized {
18    ///     id: Int!
19    ///     name: String!
20    /// }
21    ///
22    /// type Query {
23    ///    user(id: ID!): User
24    /// }
25    /// ```
26    ///
27    /// The node type name is `User`.
28    pub fn type_name(&self) -> &str {
29        &self.definition.type_name
30    }
31
32    /// The metadata passed to the `@authorized` directive. The metadata is
33    /// serialized as a JSON object. This method will deserialize the metadata
34    /// into either `serde_json::Value` or a custom struct.
35    ///
36    /// For the following GraphQL schema:
37    ///
38    /// ```graphql
39    /// type User @authorized(metadata: { role: "admin" }) {
40    ///     id: Int!
41    ///     name: String!
42    /// }
43    ///
44    /// type Query {
45    ///    user(id: ID!): User
46    /// }
47    /// ```
48    ///
49    /// When executing a query like:
50    ///
51    /// ```graphql
52    /// query {
53    ///   user(id: "123") { id }
54    /// }
55    /// ```
56    ///
57    /// The metadata is `{"role": "admin"}`.
58    ///
59    /// The metadata can be deserialized into a custom struct:
60    ///
61    /// ```rust
62    /// #[derive(serde::Deserialize)]
63    /// #[serde(untagged, rename = "snake_case")]
64    /// enum Role {
65    ///    Admin,
66    ///    User,
67    /// }
68    ///
69    /// #[derive(serde::Deserialize)]
70    /// struct Metadata {
71    ///    role: Role,
72    /// }
73    ///
74    /// # fn foo(arguments: grafbase_hooks::EdgePreExecutionArguments) -> Result<(), serde_json::Error> {
75    /// let arguments: Metadata = arguments.metadata()?;
76    /// # Ok(())
77    /// # }
78    /// ```
79    pub fn metadata<'a, T>(&'a self) -> Result<T, serde_json::Error>
80    where
81        T: serde::Deserialize<'a>,
82    {
83        serde_json::from_str(&self.metadata)
84    }
85}