Fun with Stamps. Episode 24. New “name” feature

Vasyl Boroviak
3 min readSep 16, 2018

Hello. I’m developer Vasyl Boroviak and welcome to the twenty fourth episode of Vasyl Boroviak presents Fun with Stamps.

TL;DR: Now you can easily set MyStamp.name property like this:

const MyGateway = stampit({
name: "SmsGateway"
})
MyGateway.name === "SmsGateway" // this used be hard to set

Available now in stampit@4.2.0 and @stamp/it@1.1.0. See docs at https://stampit.js.org

I find myself setting name of my stamps very often. Usually I use this package: https://www.npmjs.com/package/@stamp/named

import stampit from "@stamp/it"  // or "stampit"
import {setName} from "@stamp/named" // we will get rid of this line
import bunyan from "bunyan"
const HasLog = stampit({
init(_, {stamp}) {
// this will set logger name to "SmsGateway"
this.log = bunyan.createLogger({name: stamp.name})
}
})
const SmsGateway = stampit(HasLog, setName("SmsGateway"), {
props: ...
methods: ...
})

The code above adds HasLog behaviour which simply initialises a bunyan logger instance for each gateway instance. However, bunyan requires you to give it a name. So, I’m taking the logger name from the stamp’s name. In this case “SmsGateway”. I find this trick neat and concise. (Take that classic classes! You can’t do anything like that!)

Starting today no extra @stamp/named package needed! Just pass name: "StampName" to stampit.

import stampit from "@stamp/it"  // or "stampit"
import bunyan from "bunyan"
const HasLog = stampit({
init(_, {stamp}) {
// this will set logger name to "SmsGateway"
this.log = bunyan.createLogger({name: stamp.name});
}
})
const SmsGateway = stampit(HasLog, {
name: "SmsGateway",
props: ...
methods: ...
})

Gotchas

  • Won’t work in ES5 environments (like IE11). The name will always be “Stamp”. Name of a function can be set only in ≥ES6 environments.
  • This code doesn’t work in JavaScript in general: SmsGateway.name = “bla”. Because Function.name is a special protected property.
  • Composing with SmsGateway will inherit its name:
const TwillioGateway = SmsGateway.compose( ... )TwillioGateway.name === "SmsGateway" // Oops!

or

const TwillioGateway = stampit({
props: ...
method: ...
...
},
SmsGateway // composing with a stamp which has a non-default name
)
TwillioGateway.name === "SmsGateway" // Oops!

You just need to overwrite it:

const TwillioGateway = SmsGateway.compose({
name: "TwillioGateway",
...
})

Have fun with stamps!

--

--