Share your repls and programming experiences

← Back to all posts
Concept with Thunks
dotnetCarpenter (0)

So I codified [a concept using Thunks], since I am a lot more used to handle functions than ADTs. My plan was to get the concept, that I knew I wanted, to run using Thunks, then Promises and finally with Futures.

In the [Thunk concept], I have mocked stripeMock and sendResponse. There is 3 test-cases. campaign1 is valid data. In campaign2 the description property has to be removed or the Stripe call will fail and lastly, there is campaign3 which does not contain an url and therefore is invalid.

We can see in the console output that the Stripe mock has been called since that function adds stripe: true to the data. In the invalid case, campaign3 stripe is never called.

The common data structure used by all functions is StructHTTPSend (variable name suggestions are welcome). That is the data structure that sendResponse accept, so at any time in a flow, we can call sendResponse and send data to the client. This is useful for communicating errors.

class StructHTTPSend {
  constructor({ headers = {}, status = 200, body = "" }) {
    this.headers = headers;
    this.status = status;
    this.body = body;
  }
}

Constrasting the initial code for measure and dealing with data structure in the flow, the following is simpler, at least to me:

const measure = (label) => (io) => {
  return () => {
    const timing = new ServerTiming();
    timing.startTimer(label);
    const value = io(); // do Stripe call
    timing.stopTimer(label);

    return [
      new StructHTTPSend({
        headers: { "Server-Timing": timing.generateHeader() }
      }),
      value
    ];
  };
};

...

const flow = S.pipe([
	// Either (StructHTTPSend StructHTTPSend)
	checkCampaign,
	// Either (StructHTTPSend Thunk (Stripe -> StructHTTPSend))
	S.map((structHttpSend) => () => stripeMock(structHttpSend)),
	// Either (measure (Thunk (Stripe -> StructHTTPSend)))
	S.map(measure("Create cAmpaign")),
	// we need a Monad before we can use S.chain() not Thunk
	S.map(
		S.map(([timingHeader, stripeResponse]) =>
			mergeHttpSend(timingHeader)(stripeResponse)
		)
	)
]);