/* submit function checking is value JSON, if it is not, converting to it, parsing, using models IsJson and Jsonic, then ussing ajax and POST to send data to server side*/ handleSubmit (event) { event.preventDefault() self = this var data = this.state.text console.log('1:', data) try { var goodJson = Jsonic(data) } catch (error) { alert('error : data must be valid JSON: \n' + ' 1 example : {"foo":"bar", "red":1} \n' + ' 2 example : {foo:"bar", red:1} \n' + ' 3 example : foo:bar, red:1 \n' + ' ' + error) return false } $.ajax({ type: 'POST', url: '/data', data: goodJson, success: (data) => { this.setState({data: data}) console.log('3:', data) }, error: (xhr, status, err) => { console.error('/data', status, err.toString()) } }) alert('your data submitted successfuly \n' + data ) var newItems = this.state.items.concat(data) this.setState({ text: '', items: newItems}) console.log('submitted data: ', data) }
export const extractParams = param => { const matchParam = param.match(/^(".*"|'.*'|\S+)\s?(:|=>)\s([^$]*)$/) if (!matchParam) return {} const [, paramName, delimiter, paramValue] = matchParam try { const json = '{' + paramName + (paramName.endsWith(':') ? ' ' : ': ') + paramValue + '}' const res = jsonic(json) const key = Object.keys(res)[0] const value = res[key] return { key, value, isFn: delimiter ? delimiter.includes('=>') : false, originalParamValue: paramValue } } catch (e) { return { key: paramName, value: paramValue, isFn: delimiter ? delimiter.includes('=>') : false, originalParamValue: paramValue } } }
req.on('end', function() { try { var bufstr = buf.join('') var bodydata = 0 < bufstr.length ? tu.parseJSON(seneca,'req-body',bufstr) : {} if( util.isError(bodydata) ) { var out = tu.prepare_response(seneca,{}) out.input = bufstr out.error = error('invalid_json',{input:bufstr}) send_response(res,out,{}) return; } req.body = _.extend( {}, bodydata, (req.query && req.query.args$) ? jsonic(req.query.args$) : {}, req.query||{} ) next(); } catch(err) { err.body = err.message+': '+bufstr err.status = 400 next(err) } })
function FirebaseInit(option, cb) { if ('function' == typeof option) { cb = option option = {} } option = option || {} if (typeof option === 'string') { option = jsonic('' + option) } var name = option.name || firebaseConfig.name || convar('firebase.name') || undefined var url = option.url || firebaseConfig.url || convar('firebase.url') || name && 'https://' + name + '.firebaseio.com' || undefined var config = { url: url || convar('firebase.url', 'Firebase name or url config required.'), path: option.path || firebaseConfig.path || convar('firebase.path'), token: option.token || firebaseConfig.token || convar('firebase.token'), custom: option.custom || firebaseConfig.custom || convar('firebase.custom') } builder(config, function(err, client) { if (cb) { cb(err, client) } else if (err) { throw err } }); }
exports.parsePattern = function parse_pattern (instance, args, normaspec, fixed) { args = Norma('{strargs:s? objargs:o? moreobjargs:o? ' + (normaspec || '') + '}', args) try { return _.extend( args, { pattern: _.extend( {}, // Precedence of arguments in add,act is left-to-right args.moreobjargs ? args.moreobjargs : {}, args.objargs ? args.objargs : {}, args.strargs ? Jsonic(args.strargs) : {}, fixed || {}) }) } catch (e) { var col = (e.line === 1) ? e.column - 1 : e.column throw internals.error('add_string_pattern_syntax', { argstr: args, syntax: e.message, line: e.line, col: col }) } }
function convar(name, requiredMessage, exitCode, logger) { var val = envar(name) || envar(name.toUpperCase()) || envar(name.toLowerCase()) if (requiredMessage && typeof val === 'undefined') { var type = toType(requiredMessage) if ('string' !== type && 'error' !== type) { requiredMessage = name + ' required via default, config, environment variable, package, npm or cli' } logger = logger || console.log if (exitCode) { logger(requiredMessage) process.exit(exitCode) } else { logger(requiredMessage) if ('error' != type) requiredMessage = new Error(requiredMessage) throw requiredMessage } } if ('string' === typeof val && (val.substr(0,1) == "{" || val.indexOf('://') < 0)) { try { var json = jsonic(val) val = json } catch(e) { } } return val }
requestWithEncoding(options, function(err, data) { if (err) { ac_callback(err, null); } else { data = data.toString(); if(debug) console.log("apiinfo = " + data); var obj = jsonic(data); var sells = obj.defaultModel.sellCountDO.sellCount; var priceInfos = obj.defaultModel.itemPriceResultDO.priceInfo; var priceInfo; for (var key in priceInfos) { priceInfo = priceInfos[key]; break; } var price; if(priceInfo.promotionList === undefined) { price = priceInfo.price; resObj.price_del = ''; } else { price = priceInfo.promotionList[0].price; } resObj.price = price; resObj.sells = sells; console.log("price = " + price + " sells="+sells); ac_callback(null, resObj); } });
wsclient.serviceHandlers.messageReceived = function(message) { websocketLastMessage = (new Date()).getTime(); try { var data = jsonic(message.utf8Data); if (data && data.M) { data.M.forEach(function(M) { if (websocketGlobalTickerCallback) { websocketGlobalTickerCallback(M, wsclient); } if (websocketMarketsCallbacks.length > 0) { websocketMarketsCallbacks.forEach(function(callback) { callback(M, wsclient); }); } }); } else { // ((opts.verbose) ? console.log('Unhandled data', data) : ''); if (websocketGlobalTickerCallback) { websocketGlobalTickerCallback({'unhandled_data' : data}, wsclient); } if (websocketMarketsCallbacks.length > 0) { websocketMarketsCallbacks.forEach(function(callback) { callback({'unhandled_data' : data}, wsclient); }); } } } catch (e) { ((opts.verbose) ? console.error(e) : ''); } return false; };
function load_options (from) { var out = {} if (from.match(/\.json$/i)) { // this is deliberate, options are ALWAYS loaded synchronously var text = Fs.readFileSync(from).toString() out = Jsonic(text) } else if (from.match(/\.js$/i)) { if (!from.match(/^\//)) { from = './' + from } try { out = callmodule.require(from) } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { throw error(e, 'require_options', { from: from, module: callmodule }) } } } return out }
function formController(options, callback) { if (typeof options == 'string') { options = options.replace('.js', '') // drop trailing .js if any options = jsonic(options) } options = options || {} options.type = options.type || 'basic' options.module = options.module || 'myModule' options.controller = options.controller || 'myController' var type = options.type if (type.indexOf('.') >= 0 || type.indexOf('/') >= 0) { callback('Invalid formController type: ' + type) } function renderTemplate(type, data) { var result = compliedTemplate[type](data) callback(null, result) } if (compliedTemplate[type]) { renderTemplate(type, options) } else { var templateFile = path.normalize(__dirname + '/templates/controller/' + type + '.js') fs.fileExists(templateFile, function(exists) { fs.readFileSync(templateFile, 'utf8', function(err, template) { compliedTemplate[type] = _.template(template) }) }) } }
_.each(patterns, function (pattern) { pattern = _.isString(pattern) ? Jsonic(pattern) : pattern pins = pins.concat(_.map(private$.actrouter.list(pattern), function (desc) { return desc.match } )) })
exports.list = function (args) { args = _.isString(args) ? Jsonic(args) : args var found = this.private$.actrouter.list(args) found = _.map(found, 'match') return found }
function make_pin_handler (pin, handler) { pin = _.isObject(pin) ? pin : Jsonic(pin) var pinstr = Common.argpattern(pin) return function () { if (('' + arguments[ log_index.pin ]).indexOf(pinstr) !== -1) { return handler.apply(this, arguments) } } }
requestWithEncoding(options, function(err, data) { if (err) { ac_callback(err, null); } else { data = data.toString(); var reviews = findStr(data, "jsonp197(", ")").trim(); var obj = jsonic(reviews); resObj.reviews = obj.dsr.rateTotal; console.log("reviews = " + resObj.reviews); ac_callback(null, resObj, options); } });
const resolveAndStoreJsonValue = (param, put, resolve, reject) => { try { const json = `{${param}}` const res = jsonic(json) put(update(res)) return resolve({ result: res, type: 'param' }) } catch (e) { return reject( new Error('Could not parse input. Usage: `:param x => 2`. ' + e) ) } }
requestWithEncoding(options, function(err, data) { if (err) { ac_callback(err, null); } else { if(debug) console.log("apiinfo = " + data); var sells = findStr(data, "$callback(", ");").trim(); var obj = jsonic(sells); var sells = obj.quantity.confirmGoods; console.log("sells = " + sells); resObj.sells = sells; ac_callback(null, resObj); } });
const p = new Promise((resolve, reject) => { if (/^"?\{[^}]*\}"?$/.test(param)) { // JSON object string {"x": 2, "y":"string"} try { const res = jsonic(param.replace(/^"/, '').replace(/"$/, '')) // Remove any surrounding quotes put(replace(res)) return resolve({ result: res, type: 'params' }) } catch (e) { return reject( new Error( 'Could not parse input. Usage: `:params {"x":1,"y":"string"}`. ' + e ) ) } } else { // Single param const { key, value, isFn, originalParamValue } = extractParams(param) if (!isFn || !key || value === undefined) { return resolveAndStoreJsonValue(param, put, resolve, reject) } try { const cypherStatement = mapParamToCypherStatement( key, originalParamValue ) bolt .routedWriteTransaction( cypherStatement, {}, { useCypherThread: false, requestId: action.requestId, cancelable: false } ) .then(res => { let obj = {} res.records.forEach(record => { obj[key] = record.get(key) }) const result = recursivelyTypeGraphItems(obj) put(update(result)) resolve({ result, type: 'param' }) }) .catch(e => reject(e)) } catch (e) { reject(new Error('Could not parse input. Usage: `:param x => 2`. ' + e)) } } })
function findInfoObject(content) { let lastOffset = 0; while (true) { const scriptStart = content.indexOf('<script type="text/javascript">', lastOffset); if (scriptStart === -1) return null; const scriptEnd = content.indexOf('</script>', scriptStart); const scriptContent = content.slice(scriptStart + 31, scriptEnd); if (scriptContent.indexOf('window.DR') !== -1) { return jsonic(scriptContent.slice(12, -1)); } lastOffset = scriptEnd; } }
handleSubmit (event) { event.preventDefault() var name = this.state.input1 var value = this.state.input2 var tag = this.state.input3 try { var values = Jsonic(value) var tags = Jsonic(tag) } catch (error) { alert('error : data must be valid not JSON: \n' + ' 1 example : {"foo":"bar", "red":1} \n' + ' 2 example : {foo:"bar", red:1} \n' + ' 3 example : foo:bar, red:1 \n' + ' ' + error) return false } var total = {name, values, tags} var goodJson = Jsonic(total) console.log('Submitted data:', goodJson) $.ajax({ type: 'POST', url: '/data', data: goodJson, success: (data) => { this.setState({data: data}) console.log('2:', data) }, error: (xhr, status, err) => { console.error('/data', status, err.toString()) } }) alert('your data submitted successfuly \n' + Jsonic.stringify(total) ) this.setState({ input1: '', input2: '', input3: ''}); console.log('submitted form has value: ', total); }
function expandtype(name, ctx, line) { if (typeof name == 'string' && name.slice(-2) == '[]') return { _type:name, _array:name.slice(0,-2) } if (typeof name == 'string' && name.slice(0,1) == '{' && name.slice(-1) == '}') { var type = null; try { type = jsonic(name); } catch (e) { console.log(e, 'can not parse type definition', name); } if (type) { var fn = srcstack[srcstack.length-1].fn.split('/').slice(-1)[0].split('.')[0]; fix_custom_type_name(type, fn, line); return type; } } if (name == 'number' || name == 'string' || name == 'bool' || name == 'none' || name == 'null') return name; if (name == 'table') return { _type:'table' }; if (typeof name == 'string') { var q = findtype(name, ctx); if (q) return q; var a = name.split('.'); var t = findtype(a[0], ctx);// ctx.types.a[0]; for (var j = 1; j < a.length; j++) { //TODO: not needed /*var o = t; var q; do { q = o[a[j]] console.log('will try super', o._super); o = o._super && findtype(o._super, ctx); } while(o && !t);*/ t = t[a[j]]; } return t; } return name; }
function make_patkey ( seneca, pat ) { if ( _.isString( pat ) ) { pat = Jsonic(pat) } var keys = _.keys(seneca.util.clean(pat)).sort() var cleanpat = {} _.each( keys, function (k) { cleanpat[k] = pat[k] }) var patkey = seneca.util.pattern( cleanpat ) return patkey }
function processBadJSONResponse(body, cb) { try { var jsonic = require('jsonic'); respJSON = jsonic(body); if(respJSON != null) { processJSONResponse(respJSON, cb); } else { console.log("JSONIC parsing failed. Falling back to XML parsing.") processXMLResponse(body,cb); } } catch (ex) { console.log("JSONIC threw an exception. Falling back to XML parsing.") processXMLResponse(body,cb); } }
exports.find = function(pattern, flags) { var seneca = this var pat = _.isString(pattern) ? Jsonic(pattern) : pattern pat = seneca.util.clean(pat) pat = pat || {} var actdef = seneca.private$.actrouter.find(pat, flags && flags.exact) if (!actdef) { actdef = seneca.private$.actrouter.find({}) } return actdef }
// string args override object args function parse_pattern(instance,args,normaspec,fixed) { args = norma('{strargs:s? objargs:o? '+(normaspec||'')+'}', args) try { return _.extend( args, { pattern: _.extend( args.objargs ? args.objargs : {}, args.strargs ? jsonic( args.strargs ) : {}, fixed || {} ) }) } catch( e ) { var col = 1==e.line?e.column-1:e.column throw instance.fail('add_string_pattern_syntax',{argstr:args,syntax:e.message,line:e.line,col:col}) } }
admin.eval = function (rawCmd, context, filename, callback) { // make sure we have a server connection // before we try to process any commands if (!admin.server.socket.connected) { return callback(null, 'no connection'); } // cmd comes in as (COMMAND)/n // removing the container ()\n characters rawCmd = rawCmd.substr(1); cmd = rawCmd.substr(0, rawCmd.length-2); if (rawCmd) { try { // using jsonic library, allows malformed json cmdJSON = jsonic(rawCmd); // passing command to server, on response will fire console callback admin.server.emit('command', cmdJSON); } catch (e) { // error parsing json, pass it to console callback return callback(null, e); } // only need to bind these once, since callback is always same function if (!admin.callbackInit) { admin.callbackInit = true; admin.server.on('response', function (response) { callback(null, response.value); }); admin.server.on('disconnect', function (response) { callback(null, 'server disconnected'); }); admin.server.on('connect', function (response) { callback(null, 'server reconnected'); }); } } else { // no command, blank line callback(undefined, undefined); } };
exports.find = function (inargs, inflags) { var seneca = this var args = inargs || {} var flags = inflags || {} if (_.isString(inargs)) { args = Jsonic(inargs) } args = seneca.util.clean(args) var actmeta = seneca.private$.actrouter.find(args) if (!actmeta && flags.catchall) { actmeta = seneca.private$.actrouter.find({}) } return actmeta }
function parse_command_line (spec, parsedSpec) { var logSpec = _.isArray(spec) ? spec[0] : spec if (_.isString(logSpec)) { try { parsedSpec.log = Jsonic(logSpec) } catch (e) { parsedSpec.log = {} } return } if (_.isObject(logSpec)) { parsedSpec.log = {} var logType = Object.keys(logSpec.level || logSpec) if (logType.length > 0) { parsedSpec.log = { level: logType[0] } } } }
function make_fn (self, origargs) { var args = Common.parsePattern(self, origargs, 'fn:f?') var actargs = _.extend( {}, args.moreobjargs ? args.moreobjargs : {}, args.objargs ? args.objargs : {}, args.strargs ? Jsonic(args.strargs) : {} ) var fn if (args.fn) { fn = function (data, done) { return args.fn.call(self, data, done) } } else { fn = function (data, done) { if (args.strargs) { /*eslint-disable */ var $ = data /*eslint-enable */ _.each(actargs, function (v, k) { if (_.isString(v) && v.indexOf('$.') === 0) { /*eslint-disable */ actargs[k] = eval(v) /*eslint-enable */ } }) } self.act(actargs, done) return true } fn.nm = args.strargs } return fn }
function emit(inp){ if (isjson(inp)){ var emit = Emitter() inp = jsonic.stringify(inp) if (inp && inp !== ''){ var input = function(inp) { emit.emit(jsonic(inp)) } input(inp) } } else { try { var json = jsonic(inp) var emit = Emitter() emit.emit(json) } catch (e) { console.log(e) } } }
requestWithEncoding(options, function(err, data) { if (err) { ac_callback(err, null); } else { data = data.toString(); if(debug) console.log("data = " + data); if(obj.data.promotion && obj.data.promotion.promoData){ var reviews = findStr(data, "onSibRequestSuccess(", ");").trim(); var obj = jsonic(reviews); var start = obj.data.promotion.promoData.def[0].start; var price; if(start) { price = obj.data.promotion.promoData.def[0].price; } else { price = resObj.price_del; resObj.price_del = ''; } console.log("price = " + price); resObj.price = price; } ac_callback(null, resObj, options); } });