0

In MirageJS I am trying to create a factory for a simple array model.

Current code

Here is my code:

  let server = new Server({
    models: {
      usertab: Model
    },

    factories: {
      usertab: Factory.extend( function(i) { return i } ),
    },

    seeds(server) {
      server.createList("tab", 3)
    },

    routes() {
      this.get("api/usertabs", (schema) => {
        return schema.usertabs.all()
      })
    }
    
})

Current result

The above code returns a list of objects with an id key under the usertabs key:

{ 
  usertabs: [
    {id: "1"},
    {id: "2"},
    {id: "3"},
  ]
}

Wanted Result

I want to seed the array with simple incrementing numbers so the return value when using GET api/usertabs will return:

["1","2","3"]

For some reason there is no api documentation for Factory only a guide. The only examples I could find are ones that create arrays of objects.

Progman
  • 16,827
  • 6
  • 33
  • 48
hitautodestruct
  • 20,081
  • 13
  • 69
  • 93
  • you can convert the usertabs object to array, `return schema.usertabs.all().map(u => u.id)` – Vivek Bani Jul 29 '20 at 20:28
  • @RajdeepDebnath good idea! Although, I wonder if there is a more generic way using the `Factory` class. – hitautodestruct Jul 30 '20 at 08:57
  • if you store any entity in schema.db, id will be added to that entity; id works like a primary key to facilitate further crud operations like edit,delete etc. If you are not required to maintain state you can simple return an array, do not store in in db – Vivek Bani Jul 30 '20 at 15:02

1 Answers1

0
 this.get("api/usertabs", (schema) => {
        return schema.db.usertabs.map(item => item.id);
      })

will return an array in stead of an object containing an array. it is described in more detail here: https://miragejs.com/docs/main-concepts/database/

Hendrik
  • 139
  • 1
  • 5