ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
136 stars 64 forks source link

Make `context.resolve` Method a Dependently-Typed Method #4108

Open ThisaruGuruge opened 1 year ago

ThisaruGuruge commented 1 year ago

Description:

The resolve method

The graphql:Context has a resolve method to resolve a field value. This method is used in interceptors to resolve the field value and then process it before returning. Currently, the method is returning the anydata type and the developer has to manually check the type.

import ballerina/graphql;

readonly service class FooInterceptor {
    *graphql:Interceptor;

    isolated remote function execute(graphql:Context context, graphql:Field 'field) anydata|error {
        var data = context.resolve('field);
        if data is int {
            return data + 5;
        }
        return data;
    }
}

We can improve the DX by making this resolve method a dependently-typed method.

import ballerina/graphql;

readonly service class FooInterceptor {
    *graphql:Interceptor;

    isolated remote function execute(graphql:Context context, graphql:Field 'field) anydata|error {
        int data = context.resolve('field);
        return data + 5;
    }
}

The get Method

This should also applied to the context.get method, where currently it returns a value:Cloneable|isolated object {}|Error value. The current recommendation is the use it as the following:

import ballerina/graphql;

service graphql:Service on new graphql:Listener(9090) {
    resource function get foo(graphql:Context context) returns string {
        string token = check context.get("token").ensureType();
    }
}

Although this works, we can improve the developer experience by making it a dependently typed function where the user can do the following:

import ballerina/graphql;

service graphql:Service on new graphql:Listener(9090) {
    resource function get foo(graphql:Context context) returns string {
        string token = check context.get("token");
    }
}
ThisaruGuruge commented 1 year ago

We may introduce a new API (resolveWithType) for this to support backward compatibility.

ThisaruGuruge commented 1 year ago

We can also make the context.get() method dependently-typed by introducing similar method: getWithType()

ThisaruGuruge commented 6 months ago

We can also make the context.get() method dependently-typed by introducing similar method: getWithType()

Updating the original issue with this requirement.