0

I'm implementing service between a view and a Rest API.

Beside, i'm completly new to stamp programming and i'm in search of some advices about this sort of code:

import {compose, methods} from '@stamp/it'
import ArgOverProp from '@stamp/arg-over-prop'
import {template} from 'lodash'

const createLogger = name => (...args) => console.log('['+ name + ']', ...args)

const HasHttpClient = ArgOverProp.argOverProp('httpClient')
const HasApiVersion = ArgOverProp.argOverProp('apiVersion')
const HasUrl = ArgOverProp.argOverProp('url')

const UseRestApi = compose(HasHttpClient, HasApiVersion, HasUrl).init([
  function () {
    this.getUrl = template(this.url)
    this.useRestApiLog = createLogger('UseRestApi')
  }
]).methods({
  query: function query(method, {params, headers, body}) {
    const {apiVersion} = this
    const q = {
      baseURL: this.getUrl({apiVersion}),
      method,
      ...params != null && {params},
      ...headers != null && {headers},
      ...body != null && {body}
    }
    this.useRestApiLog('request config:', q)
    return q
  }
})

const WithGetOperation = compose(UseRestApi).init([
  function () {
    this.withGetOperationLog = createLogger('WithGetOperation')
  }
]).methods({
  'get': function get ({params}) {
    const q = this.query('get', {headers: {'Accept': 'application/json'}, params})
    this.withGetOperationLog('getting data')
    return this.httpClient(q)
  } 
})

const CustomerRestApi = compose(WithGetOperation).init([
  function () {
    this.customerRestApiLog = createLogger('CustomerRestApi')
  }
]).methods({
  all: function all() {
    this.customerRestApiLog('get all customers')
    return this.get({params: {page: 1, limit: 15}})
  }
})

const customerProvider = CustomerRestApi({
  url: 'http://sample.com/<%=apiVersion%>/customers',
  apiVersion: 'v1',
  httpClient: function(config) {
    return Promise.resolve({
      status: 200,
      config
    })
  }
})

const appLog = createLogger('APP')

customerProvider.all()
  .then(r => appLog('HTTP response code:', r.status))

Am i in the right directions?

Especially, the createLogger thing seems ugly!

How to inject a prefixed logger into each stamp ? How to extend that to warn, error, ... methods ?

Sté
  • 195
  • 11
  • https://codereview.stackexchange.com would be a better place for this question. – Jai Jan 31 '18 at 11:41

1 Answers1

1

Your logger looks just fine. It is not necessary to create every bit as a stamp. However, if you want to make the logger as a reusable stamp then you can do the same way as ArgOverProp is implemented.

Ruffly ArgOverProp is done this way:

const ArgOverProp = stampit.statics({
  argOverProp(...args) {
    return this.deepConf({ArgOverProp: [...args]});
  }
})
.init(function (options, {stamp}) {
  const {ArgOverProp} = stamp.compose.deepConfiguration;
  for (let assignableArgName of ArgOverProp) {
    this[assignableArgName] = options[assignableArgName];
  }
});

Your logger could look like this (not necessary exactly like this):

import {argOverProp} from '@stamp/arg-over-prop';

const Logger = stampit(
  argOverProp('prefix'), 
  {
    methods: {
      log(...args){ console.log(this.prefix, ...args); },
      error(...args){ console.error(this.prefix, ...args); },
      warn(...args){ console.warn(this.prefix, ...args); }
    }
  }
);

const HasLogger = stampit.statics({
  hasLogger(name) {
    return this.conf({HasLogger: {name}});
  }
})
.init(_, {stamp}) {
  const {HasLogger} = stamp.compose.configuration;
  if (HasLogger) {
    this.logger = Logger({prefix: HasLogger.name});
  }
});

And usage:

const CustomerRestApi = stampit(
  WithGetOperation, 
  HasLogger.hasLogger('CustomerRestApi'),
  {
    methods: {
      all() {
        this.logger.log('get all customers');
        return this.get({params: {page: 1, limit: 15}});
      }
  }
);

I always prefer readability. So, the code above, I hope, is readable to you and any stampit newbie.

PS: a tip. The stampit and the stampit.compose you imported above are the same exact function. :) See source code.

Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70