stampit.js初学者需要一些指导

时间:2018-01-31 11:39:39

标签: javascript stampit.js

我在视图和Rest API之间实现服务。

除此之外,我完全是新的邮票编程,我正在寻找有关此类代码的一些建议:

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))

我正朝着正确的方向前进吗?

特别是,createLogger似乎很难看!

如何在每张邮票中注入带前缀的记录器? 如何将其扩展到warn, error, ...方法?

1 个答案:

答案 0 :(得分:1)

你的记录器看起来很好。没有必要将每个位创建为戳记。但是,如果您想将记录器作为可重复使用的标记,那么您可以采用与实现ArgOverProp相同的方式。

Ruffly ArgOverProp以这种方式完成:

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];
  }
});

你的记录器看起来像这样(不一定非常像这样):

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});
  }
});

用法:

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

我总是喜欢可读性。所以,我希望上面的代码对你和任何一个新手都是可读的。

PS:小费。上面导入的stampit和stampit.compose功能完全相同。 :)见source code