JaneJeon / objection-hashid

Objection plugin to automatically obfuscate model ids using hashids!
https://janejeon.github.io/objection-hashid
GNU Lesser General Public License v3.0
14 stars 6 forks source link

Empty id field gets passed when .select() method is used #199

Open TissuePowder opened 2 years ago

TissuePowder commented 2 years ago

As the title says, when .select(), .distinct() or such methods are used, an empty id field is included in the returned data.

Basemodel:

class BaseModel extends authorize(hashid(Model)) {
  static get hashIdMinLength() {
    return 5;
  }
}

Code:

const meals = await Meal.query().select('quantity');

Current output:

[
  {
    "quantity": 1,
    "id": ""
  },
  {
    "quantity": 1,
    "id": ""
  },
  {
    "quantity": 1,
    "id": ""
  }
]

Expected output:

[
  {
    "quantity": 1
  },
  {
    "quantity": 1
  },
  {
    "quantity": 1
  }
]

Using objection-hashid 3.0.2, postgresql 14.3

JaneJeon commented 2 years ago

Makes sense. Should require a simple change in https://github.com/JaneJeon/objection-hashid/blob/master/index.js#L55 to "gate" setting any properties so that it's only run if the property was present in the original object as well. Mind raising a quick PR?

TissuePowder commented 2 years ago

Looking at the code, will this do?

if (this.constructor.hashIdField) {
    obj.hasOwnProperty(this.constructor.hashIdField) && set(obj, this.constructor.hashIdField, this.hashId)
}

this.constructor.hashedFields.forEach(field => {
    const encoded = this.constructor._hashIdInstance.encode(get(obj, field))
    obj.hasOwnProperty(field) && set(obj, field, encoded)
})

I am not sure if there's any optimization or pattern you would want to follow, or would want to recheck some other parts of code, so just do it yourself if you don't mind.

JaneJeon commented 2 years ago

Should work, yeah. Just make sure to test your specific use case as well (the select())

TissuePowder commented 2 years ago

Checked some time after I commented that. Worked as expected. Though, as I said, if you want to modify it in your preferred (or any better) way, please do it and make the commit.

JaneJeon commented 2 years ago

Cool, mind publishing the PR?

TissuePowder commented 2 years ago

Done. #200