bencodezen / vue-enterprise-boilerplate

An ever-evolving, very opinionated architecture and dev environment for new Vue SPA projects using Vue CLI.
7.78k stars 1.32k forks source link

Query and router params type casting #16

Closed jnarowski closed 6 years ago

jnarowski commented 6 years ago

When getting data from the router, it seems that the params are all strings. I'm not using type script but find the need for some sort of casting library to ensure that the params I get from the query (or anywhere else in the router) follow proper type casing.

Right now, I'm doing this kludge: `const { filters } = this.$route.query

if (filters.site_id) { filters.site_id = parseInt(filters.site_id) }`

Example: `const structure = { site_id: Number }

const castedQuery = cast(structure, this.$route.query)`

I think integration with some simple form of casting library could be a huge help for keeping params consistent across enterprise applications.

chrisvfritz commented 6 years ago

If it's just a single route that needs this, I usually recommend a computed property that returns normalized query params. Otherwise, you could share models between routes similar to:

function RouteIssue(route) {
  const { params } = route
  this.id = parseInt(params.id)
  this.userName = '@' + params.user
  this.repoName = params.repo
}

That could be used for a GitHub issue, for example. Then to create a normalized issue:

const issue = new RouteIssue(this.$route)

That's flexible enough to allow you to do a lot of things other than casting too. 🙂

jnarowski commented 6 years ago

Thx, that makes sense. Would you just put these in a utils folder? Or perhaps within the router folder?

router/casters or something like that?

chrisvfritz commented 6 years ago

They can go in utils if you just have a few, but I usually create a src/models folder for these.

jnarowski commented 6 years ago

So you'd consider this casted object a model then? Originally I was just looking for a way to standardize params from the route but this feels like a bigger conversation now relating to models?

Would an example of models make sense for the boilerplate or is that too specific per project?

chrisvfritz commented 6 years ago

Models are a little tricky, because there are a lot of equally acceptable ways to do them and people often have strong preferences on the way they like. Many projects also never find a need for them and might use plain JS objects instead, which is why I left them out of the boilerplate (for now).