gstore-node
Search…
Typescript
gstore works great with Typescript projects. You simply need to create a Type for your schema and pass it when instantiating your Schema.
Let see it with an example
1
// user.schema.ts
2
3
import GstoreNode from 'gstore-node';
4
5
const gstore = GstoreNode();
6
7
interface UserType {
8
userName: string;
9
email: string;
10
age?: number; // optional
11
tags?: string[]; // optional
12
birthday?: Date; // optional
13
}
14
15
// Pass it on Schema creation
16
const schema = new Schema<UserType>({
17
userName: { type: String },
18
email: { type: String },
19
age: { type: Number, optional: true },
20
tags: { type: Array, optional: true },
21
birthday: { type: Date, optional: true }
22
});
23
24
const User = gstore.model('User', schema);
Copied!
The `UserType` interface is then read in many places
1
// Entity
2
const user = new User({ name: 'John' }); // TS error as "email" is not provided
3
4
// Queries
5
const query = User.query();
6
query.filter('age', '<', 'wrong string'); // TS error as "age" should be a number
7
query.filter('wrongProperty', 'some value'); // TS error as "wrongProperty" does not exist in User
8
9
// We can also specify the format of the query response ("JSON" is the default and thus optional)
10
const query = User.query<'ENTITY'>(); // Set the response format to "ENTITY"
11
12
query.run({ format: 'ENTITY' }).then(result => {
13
const { entities } = result;
14
const [user] = entities;
15
16
// "user" is an Entity instance with its methods and properties
17
user.save();
18
const name = user.name; // string
19
});
20
21
// Shortcut queries (`list()` and `findAround()`) response
22
// are automatically typed from the `format` option provided
23
User.list({ format: 'ENTITY' }).populate().then((result) => {
24
const { entities } = result;
25
const [user] = entities;
26
const age = user.age; // number
27
user.save(); // method from the entity instance
28
});
Copied!

Non explicit schemas

It you want to allow other properties apart from those declared (see explicitOnly option in the Schema options), this is how you would create your Model:
1
type UserType = {
2
userName: string;
3
email: string;
4
age?: number; // optional
5
tags?: string[]; // optional
6
birthday?: Date; // optional
7
} & {[propName: string]: any}; // Allow any other properties
8
9
// Schema with "explicitOnly" set to "false"
10
const schema = new Schema<UserType>({
11
userName: { type: String },
12
email: { type: String },
13
age: { type: Number, optional: true },
14
tags: { type: Array, optional: true },
15
birthday: { type: Date, optional: true }
16
}, { explicitOnly: false }); // explicitOnly set to "false"
17
18
const User = gstore.model('User', schema);
Copied!
Last modified 2yr ago
Copy link