very-express 0.6.9-alpha → 0.6.10-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +1,100 @@
1
1
  // {{headerComment}}
2
- import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial } from "typeorm";
2
+ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, Raw } from "typeorm";
3
3
  import { IVexRepository } from "../_types/IVexRepository.gen";
4
- import { Select, Filter, Join } from "../_types/VexRequest.gen";
4
+ import { Select, Filter, Join, FieldFilter } from "../_types/VexRequest.gen";
5
5
  import utils from "../_utils";
6
6
 
7
7
  export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements IVexRepository<T> {
8
8
  constructor(private repo: Repository<T>) {}
9
9
 
10
+ private mapOperators(filter: Filter<T>): Record<string, unknown> {
11
+ if (!filter || typeof filter !== "object") return {};
12
+ // if (Array.isArray(filter)) return filter.map(f => this.mapOperators(f));
13
+
14
+ const out: Record<string, unknown> = {};
15
+
16
+ for (const [key, val] of Object.entries(filter)) {
17
+ if (key === "$and" && Array.isArray(val)) {
18
+ out["$and"] = val.map(v => this.mapOperators(v));
19
+ continue;
20
+ }
21
+ else if (key === "$or" && Array.isArray(val)) {
22
+ out["$or"] = val.map(v => this.mapOperators(v));
23
+ continue;
24
+ }
25
+ else if (val && typeof val === "object" && !Array.isArray(val)) {
26
+ // Common mongo-like operators supported in JSON payloads
27
+ val as FieldFilter<T[Extract<keyof T, string>]>;
28
+
29
+ if (val?.$in && Array.isArray(val.$in) && val.$in.every((v: unknown) => typeof v === "string")) {
30
+ out[key] = In(val.$in);
31
+ continue;
32
+ }
33
+ if (val?.$nin && Array.isArray(val.$nin) && val.$nin.every((v: unknown) => typeof v === "string")) {
34
+ out[key] = Not(In(val.$nin));
35
+
36
+ continue;
37
+ }
38
+ if (val?.$gt) {
39
+ out[key] = MoreThan(val.$gt);
40
+ continue;
41
+ }
42
+ if (val?.$gte) {
43
+ out[key] = MoreThanOrEqual(val.$gte);
44
+ continue;
45
+ }
46
+ if (val?.$lt) {
47
+ out[key] = LessThan(val.$lt);
48
+ continue;
49
+ }
50
+ if (val?.$lte) {
51
+ out[key] = LessThanOrEqual(val.$lte);
52
+ continue;
53
+ }
54
+ if (val?.$like) {
55
+ out[key] = Like(val.$like as string);
56
+ continue;
57
+ }
58
+ // if (val?.$raw) {
59
+ // out[key] = Raw(val.$raw as string);
60
+ // continue;
61
+ // }
62
+ // Recurse for nested objects
63
+ out[key] = this.mapOperators(val);
64
+ } else {
65
+ out[key] = val;
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
10
71
  public get native(): Repository<T> {
11
72
  return this.repo;
12
73
  }
13
74
 
14
- find(filter: Filter, join?: Join, select?: Select): Promise<T[]> {
75
+ find(filter: Filter<T>, join?: Join, select?: Select): Promise<T[]> {
76
+ const where = this.mapOperators(filter) as FindOptionsWhere<T>;
15
77
  return this.repo.find({
16
- select,
17
- where: filter as FindOptionsWhere<T>,
78
+ select,
79
+ where,
18
80
  relations: join
19
81
  });
20
82
  }
21
83
 
22
- findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
84
+ findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
85
+ const where = this.mapOperators(filter) as FindOptionsWhere<T>;
23
86
  return this.repo.findOne({
24
87
  select,
25
- where: filter as FindOptionsWhere<T>,
88
+ where,
26
89
  relations: join
27
90
  });
28
91
  }
29
92
 
30
- findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
93
+ findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
94
+ const where = this.mapOperators(filter) as FindOptionsWhere<T>;
31
95
  return this.repo.findOne({
32
96
  select,
33
- where: filter as FindOptionsWhere<T>,
97
+ where,
34
98
  relations: join
35
99
  });
36
100
  }
@@ -44,7 +108,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements IVexRe
44
108
  utils.log.error("TypeOrmRepositoryAdapter.replace called without id — refuse replace entity");
45
109
  return null;
46
110
  }
47
- const existing = await this.findOne({ _id: id });
111
+ const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
48
112
  if (!existing) return null;
49
113
  return this.repo.save(this.repo.merge(existing, data as DeepPartial<T>));
50
114
  }
@@ -54,8 +118,8 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements IVexRe
54
118
  utils.log.error("TypeOrmRepositoryAdapter.update called without id — refuse update entity");
55
119
  return null;
56
120
  }
57
- await this.repo.update({ _id: id } as unknown as FindOptionsWhere<T>, data as any);
58
- return this.findOne({ _id: id });
121
+ await this.repo.update({ _id: id } as unknown as FindOptionsWhere<T>, data);
122
+ return this.findOne({ _id: id } as unknown as Filter<T>);
59
123
  }
60
124
 
61
125
  async delete(id: string | undefined): Promise<void> {
@@ -41,18 +41,15 @@ export class VexDbConnector {
41
41
 
42
42
  connectSql(): void {
43
43
  utils.log.infoSql("Connecting to SQL DB (TypeORM)...");
44
+ const sqlUrl = new URL(this.sqlUrl);
44
45
 
45
- const caRaw = this.sqlCa || undefined;
46
- let ca: string | undefined;
47
- if (caRaw) {
48
- ca = caRaw.startsWith("-----BEGIN") ? caRaw : Buffer.from(caRaw, "base64").toString("utf8");
49
- }
46
+ const ca = !this.sqlCa ? undefined : this.sqlCa.startsWith("-----BEGIN") ? this.sqlCa : Buffer.from(this.sqlCa, "base64").toString("utf8");
50
47
  const insecure = (process.env.SQL_INSECURE_TLS || "").toLowerCase() === "true";
51
- const ssl = insecure
52
- ? { rejectUnauthorized: false }
53
- : (ca ? { rejectUnauthorized: true, ca } : undefined);
48
+ const ssl = {
49
+ rejectUnauthorized: insecure ? false : true,
50
+ ca,
51
+ };
54
52
 
55
- const sqlUrl = new URL(this.sqlUrl);
56
53
  const ds = new DataSource({
57
54
  type: "postgres",
58
55
  host: sqlUrl.hostname,
@@ -10,7 +10,7 @@ import VexResponseError from "../../_types/VexResponseError.gen";
10
10
  import { IVexRepository } from "../../_types/IVexRepository.gen";
11
11
 
12
12
  import VexDb from "../VexDb.gen";
13
- import { UserEntity, User } from "../../_models/UserModel.gen";
13
+ import { UserEntity, UserWithRelations } from "../../_models/UserModel.gen";
14
14
  import { SessionEntity, Session } from "../../_models/SessionModel.gen";
15
15
 
16
16
  interface tokenObj {
@@ -22,8 +22,8 @@ interface tokenObj {
22
22
  export default class JWTService {
23
23
  private keyStore = new JWTKeyStore();
24
24
 
25
- private get userRepo(): IVexRepository<User> {
26
- return VexDb.getRepository<User>(UserEntity);
25
+ private get userRepo(): IVexRepository<UserWithRelations> {
26
+ return VexDb.getRepository<UserWithRelations>(UserEntity);
27
27
  }
28
28
  private get sessionRepo(): IVexRepository<Session> {
29
29
  return VexDb.getRepository<Session>(SessionEntity);
@@ -65,21 +65,21 @@ export default class JWTService {
65
65
  /**
66
66
  * Process of login user, assign tokens and create session.
67
67
  */
68
- public async assignTokens(user: User) {
68
+ public async assignTokens(user: UserWithRelations, provider: string): Promise<string> {
69
69
  if(!user._id) {
70
70
  throw new VexResponseError(500, null, "User Data Error, User._id missing.");
71
71
  }
72
72
 
73
73
  const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
74
74
 
75
- if (this.sessionRepo) {
76
- await this.sessionRepo.create({
77
- sessionCode,
78
- userId: user._id,
79
- provider: "local",
80
- expired: Date.now() + 5000,
81
- });
82
- }
75
+ // insert new unique session for user
76
+ await this.sessionRepo.deleteWhere({ userId: user._id });
77
+ await this.sessionRepo.create({
78
+ sessionCode,
79
+ userId: user._id,
80
+ provider: provider,
81
+ expired: Date.now() + 5000,
82
+ });
83
83
 
84
84
  // return appAuthCode to client
85
85
  const redirectPath = `${path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback")}?code=${sessionCode}`;
@@ -87,7 +87,7 @@ export default class JWTService {
87
87
  return redirectPath;
88
88
  }
89
89
 
90
- public returnToken(userProfile: User) {
90
+ public returnToken(userProfile: UserWithRelations) {
91
91
  const sanitizedProfile = this.sanitizeUser(userProfile);
92
92
  const accessToken = this.generateToken(sanitizedProfile, undefined, process.env.ACCESS_TOKEN_EXPIRE_TIME);
93
93
  const refreshToken = this.generateToken({ _id: userProfile._id }, 0, process.env.REFRESH_TOKEN_EXPIRE_TIME);
@@ -103,7 +103,7 @@ export default class JWTService {
103
103
 
104
104
  /** utils */
105
105
 
106
- public sanitizeUser(user: User) {
106
+ public sanitizeUser(user: UserWithRelations) {
107
107
  return {
108
108
  _id: user._id,
109
109
  email: user.email,
@@ -138,7 +138,7 @@ export default class JWTService {
138
138
  };
139
139
  }
140
140
 
141
- public async generateAccessToken(user: User, index?: number): Promise<tokenObj> {
141
+ public async generateAccessToken(user: UserWithRelations, index?: number): Promise<tokenObj> {
142
142
 
143
143
  const userInfo = this.sanitizeUser(user);
144
144
 
@@ -1,6 +1,6 @@
1
1
  // {{headerComment}}
2
2
  import { Profile } from "passport";
3
- import { User } from "./../../_types/User.gen";
3
+ import { User, UserWithRelations } from "./../../_types/User.gen";
4
4
 
5
5
  export interface IProfile extends Profile {
6
6
  [key: string]: any;
@@ -9,7 +9,7 @@ export interface IProfile extends Profile {
9
9
  export default class OAuthProfileMap {
10
10
 
11
11
  public map(oauthProfile: Profile) {
12
- let authProfile: User;
12
+ let authProfile: UserWithRelations;
13
13
  switch (oauthProfile.provider) {
14
14
  case "github":
15
15
  authProfile = this.GithubProfileMapping(oauthProfile);
@@ -24,8 +24,8 @@ export default class OAuthProfileMap {
24
24
  return authProfile;
25
25
  }
26
26
 
27
- private GithubProfileMapping(oauthProfile: IProfile): User {
28
- const user: User = {
27
+ private GithubProfileMapping(oauthProfile: IProfile): UserWithRelations {
28
+ const user: UserWithRelations = {
29
29
  active: true,
30
30
  userAuthProfiles: [{
31
31
  provider: oauthProfile.provider,
@@ -40,8 +40,8 @@ export default class OAuthProfileMap {
40
40
 
41
41
  return user;
42
42
  }
43
- private GoogleProfileMapping(oauthProfile: IProfile): User {
44
- const user: User = {
43
+ private GoogleProfileMapping(oauthProfile: IProfile): UserWithRelations {
44
+ const user: UserWithRelations = {
45
45
  active: true,
46
46
  userAuthProfiles: [{
47
47
  provider: oauthProfile.provider,
@@ -1,5 +1,5 @@
1
1
  // {{headerComment}}
2
- import { UserEntity, User } from "./../../_models/UserModel.gen";
2
+ import { UserEntity, User, UserWithRelations } from "./../../_models/UserModel.gen";
3
3
  import { UserAuthProfilesEntity, UserAuthProfiles } from "./../../_models/UserAuthProfilesModel.gen";
4
4
  import { IVexRepository } from "./../../_types/IVexRepository.gen";
5
5
  import JWTService from "./../auth/JWTService.gen";
@@ -9,8 +9,8 @@ import utils from "../../_utils";
9
9
 
10
10
  export default class OAuthStrategyService {
11
11
 
12
- private get userRepo(): IVexRepository<User> {
13
- return VexDb.getRepository<User>(UserEntity);
12
+ private get userRepo(): IVexRepository<UserWithRelations> {
13
+ return VexDb.getRepository<UserWithRelations>(UserEntity);
14
14
  }
15
15
 
16
16
  private get uapRepo(): IVexRepository<UserAuthProfiles> {
@@ -22,12 +22,12 @@ export default class OAuthStrategyService {
22
22
  public async verify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void): Promise<void> {
23
23
  try {
24
24
 
25
- let user: User;
25
+ let user: UserWithRelations;
26
26
  const authUser = new OAuthProfileMap().map(profile);
27
27
  const authProfile = authUser.userAuthProfiles?.[0];
28
28
 
29
29
  // find user by oauthId + provider, or fall back to email
30
- let existingUser: User | null = null;
30
+ let existingUser: UserWithRelations | null = null;
31
31
  if (authProfile?.oauthId && authProfile?.provider) {
32
32
  const matchedProfile = await this.uapRepo.findOneWhere(
33
33
  { oauthId: authProfile.oauthId, provider: authProfile.provider },
@@ -61,7 +61,7 @@ export default class OAuthStrategyService {
61
61
  }
62
62
  }
63
63
 
64
- private async createNewUser(authProfile: User): Promise<User> {
64
+ private async createNewUser(authProfile: UserWithRelations): Promise<UserWithRelations> {
65
65
  utils.log.info("OAuthVerify > createNewUser");
66
66
  const user = await this.userRepo.create(authProfile);
67
67
 
@@ -7,12 +7,12 @@ import { Select, Filter, Join } from "./VexRequest.gen";
7
7
  * Controllers and services talk only to this — the adapter layer (TypeORM/Mongoose) absorbs DB specifics.
8
8
  */
9
9
  export interface IVexRepository<T> {
10
- find(filter: Filter, join?: Join, select?: Select): Promise<T[]>;
11
- findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null>;
12
- findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null>;
10
+ find(filter: Filter<T>, join?: Join, select?: Select): Promise<T[]>;
11
+ findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
12
+ findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null>;
13
13
  create(data: Partial<T>): Promise<T>;
14
14
  replace(id: string | undefined, data: Partial<T>): Promise<T | null>;
15
15
  update(id: string | undefined, data: Partial<T>): Promise<T | null>;
16
16
  delete(id: string | undefined): Promise<void>;
17
- deleteWhere(filter: Filter): Promise<void>;
17
+ deleteWhere(filter: Filter<T>): Promise<void>;
18
18
  }
@@ -1,11 +1,31 @@
1
1
  // {{headerComment}}
2
2
 
3
+ export type FieldOperators = {
4
+ $in?: string[] | number[];
5
+ $nin?: string[] | number[];
6
+ $gt?: number | string;
7
+ $gte?: number | string;
8
+ $lt?: number | string;
9
+ $lte?: number | string;
10
+ $like?: string;
11
+ $raw?: string;
12
+ };
13
+
14
+ export type FieldFilter<V> = V & FieldOperators;
15
+
3
16
  export type Select = string[];
4
- export type Filter = Record<string, unknown>;
17
+
18
+ export type Filter<T = any> = {
19
+ [K in keyof T]?: FieldFilter<T[K]>;
20
+ } & {
21
+ $and?: Filter<T>[];
22
+ $or?: Filter<T>[];
23
+ };
24
+
5
25
  export type Join = string[];
6
26
 
7
- export default interface VexRequest {
27
+ export default interface VexRequest<T = any> {
8
28
  select?: Select;
9
- filter?: Filter;
29
+ filter?: Filter<T>;
10
30
  join?: Join;
11
31
  };
@@ -1,7 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import crypto from "crypto";
3
3
  // import log from "~/utils/logger";
4
- import { User } from "../_types/User.gen";
4
+ import { UserWithRelations } from "../_types/User.gen";
5
5
 
6
6
  /**
7
7
  * Hashes a password with a salt (e.g., user email).
@@ -25,7 +25,7 @@ export function hashPassword(
25
25
  * @returns True if the password matches, false otherwise.
26
26
  */
27
27
  export function verifyPassword(
28
- user: User,
28
+ user: UserWithRelations,
29
29
  plainPassword: string,
30
30
  ): boolean {
31
31
  if(!user.email || !user.userAuthProfiles) {
@@ -35,12 +35,6 @@
35
35
  "default": true,
36
36
  "required": true
37
37
  },
38
- "roles": {
39
- "type": "array",
40
- "items": {
41
- "type": "string"
42
- }
43
- },
44
38
  "locale": {
45
39
  "type": "string",
46
40
  "maxLength": 8
@@ -2,7 +2,7 @@
2
2
  document.addEventListener("DOMContentLoaded", function () {
3
3
  // add event listener to login button
4
4
  document.querySelector("#localLoginBtn").addEventListener("click", function () {
5
- // call api /auth/local
5
+ // call /api/auth/local
6
6
  fetch("/api/auth/local", {
7
7
  method: "POST",
8
8
  headers: {
@@ -35,7 +35,7 @@ document.addEventListener("DOMContentLoaded", function () {
35
35
  });
36
36
 
37
37
  document.querySelector("#localRegisterBtn").addEventListener("click", function () {
38
- // call api /auth/register
38
+ // call /api/auth/register
39
39
  fetch("/api/auth/register", {
40
40
  method: "POST",
41
41
  headers: {
@@ -1,11 +1,11 @@
1
1
  let jsonData = {};
2
2
 
3
3
  document.addEventListener("DOMContentLoaded", function () {
4
- jsonData = {
5
- accessToken: localStorage.getItem("accessToken"),
6
- accessTokenIndex: localStorage.getItem("accessTokenIndex"),
7
- refreshToken: localStorage.getItem("refreshToken"),
8
- refreshTokenIndex: localStorage.getItem("refreshTokenIndex"),
9
- };
10
- document.querySelector("#tokenData").innerHTML = JSON.stringify(jsonData, null, 2);
4
+ jsonData = {
5
+ accessToken: localStorage.getItem("accessToken"),
6
+ accessTokenIndex: localStorage.getItem("accessTokenIndex"),
7
+ refreshToken: localStorage.getItem("refreshToken"),
8
+ refreshTokenIndex: localStorage.getItem("refreshTokenIndex"),
9
+ };
10
+ document.querySelector("#tokenData").innerHTML = JSON.stringify(jsonData, null, 2);
11
11
  });
@@ -1,23 +1,23 @@
1
1
  document.addEventListener("DOMContentLoaded", function () {
2
- jsonPayload = {
3
- refreshToken: localStorage.getItem("refreshToken"),
4
- refreshTokenIndex: localStorage.getItem("refreshTokenIndex"),
5
- };
2
+ jsonPayload = {
3
+ refreshToken: localStorage.getItem("refreshToken"),
4
+ refreshTokenIndex: localStorage.getItem("refreshTokenIndex"),
5
+ };
6
6
 
7
- fetch("/api/auth/refresh", {
8
- method: "POST",
9
- body: JSON.stringify(jsonPayload),
10
- headers: {
11
- "Content-Type": "application/json",
12
- "Accept": "application/json",
13
- "Authorization": "Bearer " + localStorage.getItem("accessToken"),
14
- "X-Auth-Index": localStorage.getItem("accessTokenIndex")
15
- }
16
- })
17
- .then(res => res.json())
18
- .then((response) => {
19
- localStorage.setItem("accessToken", response.accessToken);
20
- localStorage.setItem("accessTokenIndex", response.accessTokenIndex);
21
- document.querySelector("#tokenData").innerHTML = JSON.stringify(response, null, 2);
22
- });
7
+ fetch("/api/auth/refresh", {
8
+ method: "POST",
9
+ body: JSON.stringify(jsonPayload),
10
+ headers: {
11
+ "Content-Type": "application/json",
12
+ "Accept": "application/json",
13
+ "Authorization": "Bearer " + localStorage.getItem("accessToken"),
14
+ "X-Auth-Index": localStorage.getItem("accessTokenIndex")
15
+ }
16
+ })
17
+ .then(res => res.json())
18
+ .then((response) => {
19
+ localStorage.setItem("accessToken", response.accessToken);
20
+ localStorage.setItem("accessTokenIndex", response.accessTokenIndex);
21
+ document.querySelector("#tokenData").innerHTML = JSON.stringify(response, null, 2);
22
+ });
23
23
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.6.9-alpha",
3
+ "version": "0.6.10-alpha",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",
package/vex.config.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "localAuth": true,
16
16
  "useHttpOnlyCookieToken": true,
17
17
  "oauthProviders": {
18
- "google": true,
18
+ "google": false,
19
19
  "github": false
20
20
  }
21
21
  },