Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to support null as default value #47

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,17 @@ var isString = function (def) {
}
}

var defaultValue = function (f, def) {
var defaultValue = function (f, def, defaultNull) {
if (f.map) return '{}'
if (f.repeated) return '[]'

switch (f.type) {
case 'string':
return isString(def) ? def : '""'
return isString(def) ? def : (defaultNull ? 'null' : '""')

case 'bool':
if (def === 'true') return 'true'
return 'false'
if (def === 'true' || def === 'false') return def
return defaultNull ? 'null' : 'false'

case 'float':
case 'double':
Expand All @@ -74,14 +74,16 @@ var defaultValue = function (f, def) {
case 'int32':
case 'sint64':
case 'sint32':
return '' + Number(def || 0)
var number = Number(def)
if (def === '' || isNaN(number)) return defaultNull ? 'null' : '0'
return String(number)

default:
return 'null'
return 'null'
}
}

module.exports = function (schema, extraEncodings) {
module.exports = function (schema, extraEncodings, defaultNull) {
var messages = {}
var enums = {}
var cache = {}
Expand Down Expand Up @@ -387,7 +389,8 @@ module.exports = function (schema, extraEncodings) {
return
}

objectKeys.push(genobj.property(f.name) + ': ' + defaultValue(f, def))
var value = defaultValue(f, def, defaultNull);
objectKeys.push(genobj.property(f.name) + ': ' + value)
})

decode()
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module.exports = function (proto, opts) {
var Messages = function () {
var self = this

compile(sch, opts.encodings || {}).forEach(function (m) {
compile(sch, opts.encodings || {}, opts.defaultNull).forEach(function (m) {
self[m.name] = flatten(m.values) || m
})
}
Expand Down