base-domain
Version:
simple module to help build Domain-Driven Design
144 lines (102 loc) • 3.6 kB
text/coffeescript
'use strict'
{ camelize } = require '../util'
###*
type of model's property
TypeInfo
base-domain
###
class TypeInfo
constructor: (, options = {}) ->
@[k] = v for k, v of options
###*
default value
{any} default
###
###*
flag not to include this prop after 'toPlainObject()'
{Boolean} omit
###
###*
Creates a function which returns TypeInfo
createType
{String} typeName
{Function(TypeInfo)}
###
: (typeName) ->
fn = (options) ->
if not options?.hasOwnProperty('default') and not options?.hasOwnProperty('omit')
options = default: options
return new TypeInfo typeName, options
fn.typeName = typeName
return fn
###*
get TypeInfo as MODEL
createModelType
{String} modelName
{Options|String} [idPropName] by default: xxxYyyId when modelName is xxx-yyy
{TypeInfo} type
###
: (modelName, options = {}) ->
if typeof options is 'string'
options = idPropName: options
options.model = modelName
options.idPropName ?= camelize(modelName, true) + 'Id'
new TypeInfo 'MODEL', options
###*
get TypeInfo as MODEL
createEnumType
{Array(String)} values
{Object|String} [idPropName] by default: xxxYyyId when modelName is xxx-yyy
{TypeInfo} type
###
: (values, options = {}) ->
if typeof options isnt 'object'
options = default: options
options.values = values
typeInfo = new TypeInfo 'ENUM', options
if not Array.isArray values
throw new Error("Invalid definition of ENUM. Values must be an array.")
numsByValue = {}
for value, i in values
if typeof value isnt 'string'
throw new Error("Invalid definition of ENUM. Values must be an array of string.")
if numsByValue[value]?
throw new Error("Invalid definition of ENUM. Value '#{value}' is duplicated.")
numsByValue[value] = i
if typeof typeInfo.default is 'string'
if not numsByValue[typeInfo.default]?
throw new Error("Invalid default value '#{typeInfo.default}' of ENUM.")
typeInfo.default = numsByValue[typeInfo.default]
if typeInfo.default? and not values[typeInfo.default]?
throw new Error("Invalid default value '#{typeInfo.default}' of ENUM.")
typeInfo.numsByValue = numsByValue
return typeInfo
###*
TYPES defines various data type, including model and array of models
key: typeName (String)
value: type TypeInfo|Function(TypeInfo)
TYPES
###
:
ANY : 'ANY'
STRING : 'STRING'
NUMBER : 'NUMBER'
BOOLEAN : 'BOOLEAN'
OBJECT : 'OBJECT'
ARRAY : 'ARRAY'
DATE : 'DATE'
BUFFER : 'BUFFER'
GEOPOINT : 'GEOPOINT'
CREATED_AT : 'CREATED_AT'
UPDATED_AT : 'UPDATED_AT'
SUB_ID : 'SUB_ID'
MODEL :
ENUM :
module.exports = TypeInfo