Giter VIP home page Giter VIP logo

ordercloud-dotnet-catalyst's Introduction

ordercloud-dotnet-catalyst

OrderCloud.Catalyst

A foundational library for building OrderCloud middleware, plugins and extensions with .NET. A toolbox of helpers for authentication, performant bulk requests, error handling, jobs, project setup, ect.

See dotnet-catalyst-examples for a starter template of a middleware project that uses this library. Targeted guides are found there.

If you're building solutions for OrderCloud using .NET and find a particular task difficult or tedious, we welcome you to suggest a feature for inclusion in this library.

Features

Use Ordercloud's authentication scheme in your own APIs.

[HttpGet("hello"), OrderCloudUserAuth(ApiRole.Shopper)]
public string SayHello() {
    return $"Hello {UserContext.Username}";  // UserContext is a property on CatalystController
}

Securely receive push notifications of events from the Ordercloud platform.

[HttpPost("webhook"), OrderCloudWebhookAuth]
public object HandleAddressSave([FromBody] WebhookPayloads.Addresses.Save<MyConfigData> payload) {
    ...
}

If OrderCloud's limit of 100 records per page is a pain point.

var orders = new OrderCloudClient(...).Orders.ListAllAsync();

Receive list requests to your API with user defined filters, search, paging, and sorting.

[HttpGet("orders"), OrderCloudUserAuth(ApiRole.Shopper)]
public async Task<ListPage<Order>> ListOrders(IListArgs args)
{
    var user = await _oc.Me.GetAsync(UserContext.AccessToken); // get user details
    args.Filters.Add(new ListFilter("FromCompanyID", user.MeUser.Buyer.ID)) // filter using the user's buyer organization ID 
    args.Filters.Add(new ListFilter("LineItemCount", ">5"))
    // list orders from an admin endpoint
    var orders = await _oc.Orders.ListAsync(OrderDirection.Incoming, null, null, null, null, args); // apply list args with an extension version of ListAsync()
    return orders;
}

Use Redis or LazyCache. Or, define your own implementation of ISimpleCache.

private ISimpleCache _cache;

[HttpGet("thing")]
public Thing GetThing(string thingID) {
    var key = $"thing-{thingID}";
    var timeToLive = TimeSpan.FromMinutes(10);
    var thing = await _cache.GetOrAddAsync(key, timeToLive, () database.GetThing(thingID));
    return thing;
}

[HttpPut("thing")]
public Thing EditThing(string thingID) {
    var key = $"thing-{thingID}";
    await _cache.RemoveAsync(thingID);
    return await database.EditThing(thingID);
}

A perfomance helper for multiple async function calls.

var cars = new List<Car>();

var maxConcurency = 20;
var minPause = 100 // ms
var carOwners = await Throttler.RunAsync(cars, minPause, maxConcurency, car => apiClient.GetCarOwner(car.ID);

Handle API errors, including unexpected ones, with a standard JSON response structure. Define your own errors.

public class AgeLimit21Exception : CatalystBaseException
{
    public AgeLimit21Exception() : base("AgeLimit21", 403, "You must be 21 years of age or older to buy this product.") { }
}

....

Require.That(user.xp.Age >= 21, new AgeLimit21Exception());

Take advantage of DataAnnotation attributes to specify validation requirements for your own custom models.

[Required(ErrorMessage = "This field is required, please try again.")]
public string RequiredField { get; set; }

Testing helpers

When writing integration tests that hit an endpoint marked with [OrderCloudUserAuth], you'll need to pass a properly formatted JWT token in the Authorization header, otherwise the call will fail. Fake tokens are a bit tedious to create, so OrderCloud.Catalyst provides a helper:

var token = FakeOrderCloudToken.Create(
    clientID: "my-client-id", 
    roles: new List<string> { "Shopper" },
    expiresUTC: DateTime.UtcNow + TimeSpan.FromHours(1),
    notValidBeforeUTC: DateTime.UtcNow - TimeSpan.FromHours(1)
);
httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", token);

ordercloud-dotnet-catalyst's People

Contributors

oliverheywood451 avatar crhistianramirez avatar lauerya avatar ivanbrygar avatar maxwmaher avatar smitbmx avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.