map<U> method

Service<Id, U> map <U>(
  1. U encoder(
    1. Data
    ),
  2. Data decoder(
    1. U
    ),
  3. {FutureOr<U> readData(
    1. RequestContext,
    2. ResponseContext
    )}
)

Creates an AnonymousService that wraps over this one, and maps input and output using two converter functions.

Handy utility for handling data in a type-safe manner.

Implementation

Service<Id, U> map<U>(U Function(Data) encoder, Data Function(U) decoder,
    {FutureOr<U> Function(RequestContext, ResponseContext) readData}) {
  readData ??= (req, res) async {
    var inner = await this.readData(req, res);
    return encoder(inner);
  };

  return AnonymousService<Id, U>(
    readData: readData,
    index: ([params]) {
      return index(params).then((it) => it.map(encoder).toList());
    },
    read: (id, [params]) {
      return read(id, params).then(encoder);
    },
    create: (data, [params]) {
      return create(decoder(data), params).then(encoder);
    },
    modify: (id, data, [params]) {
      return modify(id, decoder(data), params).then(encoder);
    },
    update: (id, data, [params]) {
      return update(id, decoder(data), params).then(encoder);
    },
    remove: (id, [params]) {
      return remove(id, params).then(encoder);
    },
  );
}