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

function string #29

Open
pgherveou opened this issue Aug 23, 2012 · 2 comments
Open

function string #29

pgherveou opened this issue Aug 23, 2012 · 2 comments

Comments

@pgherveou
Copy link
Contributor

Hi TJ
express-expose define the following function to create a string representation of objects

function string(obj) {
  if ('function' == typeof obj) {
    return obj.toString();
  } else if (obj instanceof Date) {
    return 'new Date("' + obj + '")';
  } else if (Array.isArray(obj)) {
    return '[' + obj.map(string).join(', ') + ']';
  } else if ('[object Object]' == Object.prototype.toString.call(obj)) {
    return '{' + Object.keys(obj).map(function(key){
      return '"' + key + '":' + string(obj[key]);
    }).join(', ') + '}';
  } else {
    return JSON.stringify(obj);
  }
}

This works well except when used with mongo ObjectId object, where I end up with this serialisation

window.someId = window.someId || {};
someId["_bsontype"] = "ObjectID";
someId["id"] = "OÏ�\u001a¾�Å°U\u0000\u00000";

for my use case, I could replace the Object.prototype.toString statement with obj.toString (toString return string representation on ObjectId)

...
 // else if ('[object Object]' == Object.prototype.toString.call(obj)) {
 else if ('[object Object]' == obj.toString.call(obj)) {

Could the function be exposed somehow so I can inject my customisations ?
Or do you see a better solution for this kind of issues ?

@tj
Copy link
Member

tj commented Sep 2, 2012

we should probably add regular toJSON support, that could be used

@pgherveou
Copy link
Contributor Author

That sounds like a good idea
in my case i ended up to write something like that

res.expose("me = " + (JSON.stringify(user.toJSON())) + ";");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants