Skip to content

Automatically identify pk and fks into repository layer #23

@italojs

Description

@italojs

Following the issue herbsjs/herbs-cli#26

I would like to have an automatic PK and FK identification for my herbs2knex repositories

e.g:

USERS_TABLE PRODUCTS_TABLESELES_TABLE
id name email
12 italo email@email.com
13 jhow email@email.com
14 david email@email.com
id name price
3 mouse 50
4 monitor 200
5 keyboard 40
id userId productId
34 12 3
35 12 5
36 13 3

Today we have to explicity inform what is my PK and my FK with ids and foreignKeys keys

entity("Sale", {
    id: field(Number),
    product: field(Product),
    user: field(User), 
})
// ----------------------------------------
class SaleRepository extends Repository {    
   constructor() {       
       super({            
         entity: Sale,            
         table: 'SALES_TABLE',            
         ids: ['id'], 
         foreignKeys: [{ userId: Number, productId: Number }], 
         knex: connection        
       })   
     }
}

Instead write foreignKeys: [{ userId: Number, productId: Number }] and ids: ['id'] I would like the herbs2knex identify my FKs and Pks automagically.

My sugestion

  • When we don't specify our ID/PK the herbs2knex will look for id property into father entity(Sale)
  • When we don't specify our FKs the herbs2knex will look each father's property and for each entity will look for an id property
class SaleRepository extends Repository {    
   constructor() {       
       super({            
         entity: Sale,            
         table: 'SALES_TABLE', 
         knex: connection        
       })   
     }

If we need to have complex fields like :

entity("User", {
    id: field(Number),
    [...]
    address: field(Address)
})

we can check if this have an ID property, if doesn't we just don't process it as an FK.
it makes match with herbsjs/gotu#46

future possibilities

When we identify a entity that have relations inside, we can make "lazy load/insert" into repositories too, example:

entity("Sale", {
    id: field(Number),
    product: field(Product),
    user: field(User), 
})
// ---------------------------------
const entity = saleRepository.FindByID(123)
/*
id: 123
product: {
    id: 23,
    name: 'mouse',
    price: 123.23
},
user: {
   id: 155,
   name: 'italo',
   email: 'email@dsa.com'
}
*/

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Ready to code

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions