Skip to content

Will all HTTP methods be added? #200

@Invop

Description

@Invop

Hi! I just wanted to understand whether other Http methods with authentication, context transfer, and so on will be added, or is this library limited to Post requests due to the name "Function"?

Could you please tell me why it is limited to Post requests only?

I made a crutch what it might look like

public interface IEndpoint
{
    void MapEndpoint(IEndpointRouteBuilder app);
}

public interface ITeamsFunction : IEndpoint
{
    string FunctionName { get; }
}

public abstract class TeamsFunctionBase<TBody> : ITeamsFunction
{
    public abstract string FunctionName { get; }
    protected virtual HttpMethod HTTPMethod => HttpMethod.Post;

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        var handler = async (HttpContext httpContext) =>
        {
            httpContext.Request.EnableBuffering();
            var teamsApp = httpContext.RequestServices.GetRequiredService<App>();
            var log = teamsApp.Logger.Child("functions").Child(FunctionName);

            if (httpContext.Request.Headers.Authorization.FirstOrDefault() is null)
            {
                return Results.Unauthorized();
            }

            if (!httpContext.Request.Headers.TryGetValue("X-Teams-App-Session-Id", out var appSessionId))
            {
                return Results.Unauthorized();
            }

            if (!httpContext.Request.Headers.TryGetValue("X-Teams-Page-Id", out var pageId))
            {
                return Results.Unauthorized();
            }

            var authToken = httpContext.Request.Headers.Authorization
                .FirstOrDefault()?
                .Replace("bearer ", string.Empty)
                .Replace("Bearer ", string.Empty);

            var token = new JwtSecurityTokenHandler().ReadJwtToken(authToken);

            var functionContext = new FunctionContext<TBody>(teamsApp)
            {
                Api = new(teamsApp.Api),
                Log = log,
                AppSessionId = appSessionId,
                TenantId = token.Claims.First(c => c.Type == "tid").Value,
                UserId = token.Claims.First(c => c.Type == "oid").Value,
                UserName = token.Claims.First(c => c.Type == "name").Value,
                PageId = pageId,
                AuthToken = authToken,
                Data = default
            };
            if (HTTPMethod != HttpMethod.Get)
            {
                functionContext.Data = await httpContext.Request.ReadFromJsonAsync<TBody>();
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Channel-Id", out var channelId))
            {
                functionContext.ChannelId = channelId;
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Chat-Id", out var chatId))
            {
                functionContext.ChatId = chatId;
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Meeting-Id", out var meetingId))
            {
                functionContext.MeetingId = meetingId;
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Message-Id", out var messageId))
            {
                functionContext.MessageId = messageId;
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Sub-Page-Id", out var subPageId))
            {
                functionContext.SubPageId = subPageId;
            }

            if (httpContext.Request.Headers.TryGetValue("X-Teams-Team-Id", out var teamId))
            {
                functionContext.TeamId = teamId;
            }

            log.Debug(functionContext.Data?.ToString());
            var result = await HandleAsync(functionContext, httpContext.RequestServices);

            return result;
        };

        var endpoint = $"{ApiEndpoints.FunctionsPath}/{FunctionName}";
        var routeBuilder = HTTPMethod.Method switch
        {
            "GET" => app.MapGet(endpoint, handler),
            "POST" => app.MapPost(endpoint, handler),
            "PUT" => app.MapPut(endpoint, handler),
            "DELETE" => app.MapDelete(endpoint, handler),
            "PATCH" => app.MapPatch(endpoint, handler),
            _ => throw new NotSupportedException($"HTTP method {HTTPMethod.Method} is not supported")
        };

        routeBuilder.RequireAuthorization(HostApplicationBuilderExtensions.EntraTokenAuthConstants.AuthorizationPolicy);
    }

    protected abstract Task<IResult> HandleAsync(IFunctionContext<TBody> context, IServiceProvider services);
}

public static class EndpointExtensions
{
    public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
    {
        var serviceDescriptors = assembly
            .DefinedTypes
            .Where(type => type is { IsAbstract: false, IsInterface: false } &&
                           type.IsAssignableTo(typeof(IEndpoint)))
            .Select(type => ServiceDescriptor.Transient(typeof(IEndpoint), type))
            .ToArray();

        services.TryAddEnumerable(serviceDescriptors);

        return services;
    }

    public static IApplicationBuilder MapEndpoints(
        this WebApplication app,
        RouteGroupBuilder? routeGroupBuilder = null)
    {
        var endpoints = app.Services.GetRequiredService<IEnumerable<IEndpoint>>();

        IEndpointRouteBuilder builder = routeGroupBuilder is null ? app : routeGroupBuilder;

        foreach (var endpoint in endpoints)
        {
            endpoint.MapEndpoint(builder);
        }

        return app;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions