Created
December 4, 2019 15:19
-
-
Save dennisoelkers/62f91f32a0168e18f037088317c27e13 to your computer and use it in GitHub Desktop.
IntelliJ File Template for JS Value Classes with Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow strict | |
import * as Immutable from 'immutable'; | |
type InternalState = { | |
id: string, | |
}; | |
export type ${NAME}JSON = { | |
id: string, | |
}; | |
export default class ${NAME} { | |
_value: InternalState; | |
constructor(id: \$PropertyType<InternalState, 'id'>) { | |
this._value = { id }; | |
} | |
get id() { | |
return this._value.id; | |
} | |
toBuilder() { | |
// eslint-disable-next-line no-use-before-define | |
return new Builder(Immutable.Map(this._value)); | |
} | |
static create(id: \$PropertyType<InternalState, 'id'>) { | |
return new ${NAME}(id); | |
} | |
toJSON() { | |
const { id } = this._value; | |
return { | |
id, | |
}; | |
} | |
static fromJSON(value: ${NAME}JSON) { | |
const { id } = value; | |
return ${NAME}.create(id); | |
} | |
} | |
type BuilderState = Immutable.Map<string, any>; | |
class Builder { | |
value: BuilderState; | |
constructor(value: BuilderState = Immutable.Map()) { | |
this.value = value; | |
} | |
id(value: \$PropertyType<InternalState, 'id'>) { | |
return new Builder(this.value.set('id', value)); | |
} | |
build() { | |
const { id } = this.value.toObject(); | |
return new ${NAME}(id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment