Primary key
Define what is the right property to relay on for "_ById" queries
For query and upsert data SugoiJS use primary key of the instance\query object.
The primary key is a property which decorated with @Primary()
Using the Primary key will be done by:
  1. 1.
    (Utility function) getPrimaryKey(classToUse)
    Return the primary key name from given class, if not found 'null' will be returned.
  2. 2.
    (Static method) castIdToQuery(id:string,classToUse = this)
    Will return an object with property name which is decorated with Primary as the key and the ID as the value
    classToUse - class to get the primary key from (default is this)
  3. 3.
    (static method) getIdFromQuery(query: any,classToUse = this, deleteProperty:boolean = true)
    If query contains the primary key the function will return the query primary key value.
    classToUse - class to get the primary key from (default is this).
    deleteProperty - delete primary key property from the query (default is true).
  4. 4.
    (instance method) getIdQuery():{[prop:string]:string}
    Returns a key value object of primary key and its' value for the current instance.
    if no primary key set the function will throw an exception;
Full example:
1
export class Post extends ModelAbstract{
2
@Primary()
3
public postId:string = "post-12";
4
5
public static getPostById(id:string): Promise<Post>{
6
return this.find(this.castIdToQuery(id));
7
}
8
9
public getCurrentPost(): Promise<Post>{
10
const query = getIdQuery(); // query = {postId:"post-12"}
11
return Post.find(query);
12
}
13
14
public getPrimaryKeyName(): string{
15
return getPrimaryKey(this);// result is "postId"
16
}
17
18
}
Copied!
All of the @sugoi/orm predefined methods which is mentioned before using the primary key value.
Last modified 3yr ago
Copy link