kontas-express 1.0.8 → 1.0.10

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.
Files changed (2) hide show
  1. package/dist/index.js +240 -51
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3,79 +3,116 @@
3
3
  var generateMongoRepository = (name, pluralName) => `import { ObjectId } from "mongodb"
4
4
  import { connectToDatabase, getDatabaseCollection } from "../../config"
5
5
  import type { Create${name}, Update${name}, ${pluralName}, ${name}Id } from "./${name.toLowerCase()}.schema"
6
+ import { ${name} } from "./${name.toLowerCase()}.schema"
6
7
 
7
8
  type ${name}Response<T> = {
8
- success: boolean
9
+ success: true
9
10
  message?: string
10
11
  value: T
12
+ } | {
13
+ success: false
14
+ message: string
15
+ error: unknown
16
+ value: null
11
17
  }
12
18
 
13
- export class ${name} {
14
- private collectionName = "${pluralName}"
19
+ export class ${name}Repository {
20
+ private readonly collectionName = "${pluralName}"
21
+ private collection: ReturnType<typeof getDatabaseCollection> | null = null
15
22
 
16
- async connect() {
17
- await connectToDatabase()
18
- return getDatabaseCollection(this.collectionName)
23
+ private async getCollection() {
24
+ if (!this.collection) {
25
+ await connectToDatabase()
26
+ this.collection = getDatabaseCollection(this.collectionName)
27
+ }
28
+ return this.collection
19
29
  }
20
30
 
21
- async create(data: Create${name}): Promise<${name}Response<${pluralName}>> {
22
- const collection = await this.connect()
23
-
24
- const doc = {
25
- ...data,
26
- createdAt: new Date(),
27
- updatedAt: new Date()
28
- }
29
-
30
- const result = await collection.insertOne(doc)
31
- return {
32
- success: true,
33
- message: "${name} created successfully",
34
- value: { ...doc, _id: result.insertedId } as ${pluralName}
31
+ async create(data: Readonly<Create${name}>): Promise<${name}Response<${pluralName}>> {
32
+ try {
33
+ const collection = await this.getCollection()
34
+
35
+ const doc = {
36
+ ...data,
37
+ createdAt: new Date(),
38
+ updatedAt: new Date()
39
+ } as const
40
+
41
+ const result = await collection.insertOne(doc)
42
+ return {
43
+ success: true,
44
+ message: "${name} created successfully",
45
+ value: new ${name}({ ...doc, _id: result.insertedId }) as ${pluralName}
46
+ }
47
+ } catch (error) {
48
+ return {
49
+ success: false,
50
+ message: "Failed to create ${name.toLowerCase()}",
51
+ error,
52
+ value: null
53
+ }
35
54
  }
36
55
  }
37
56
 
38
- async findAll(): Promise<${name}Response<${pluralName}[]>> {
39
- const collection = await this.connect()
40
- const docs = await collection.find({}).toArray()
57
+ async findAll(): Promise<${name}Response<${name}[]>> {
58
+ const collection = await this.getCollection()
59
+ const docs = await collection.find({}).toArray() as ${pluralName}[]
41
60
  return {
42
61
  success: true,
43
- value: docs as ${pluralName}[]
62
+ value: docs.map(doc => new ${name}(doc))
44
63
  }
45
64
  }
46
65
 
47
- async findById({ id }: ${name}Id): Promise<${name}Response<${pluralName} | null>> {
48
- const collection = await this.connect()
49
- const doc = await collection.findOne({ _id: new ObjectId(id) })
50
- return {
51
- success: true,
52
- value: doc as ${pluralName} | null
66
+ async findById({ id }: Readonly<${name}Id>): Promise<${name}Response<${name} | null>> {
67
+ try {
68
+ const collection = await this.getCollection()
69
+ const doc = await collection.findOne({ _id: new ObjectId(id) }) as ${pluralName} | null
70
+ return {
71
+ success: true,
72
+ value: doc ? new ${name}(doc) : null
73
+ }
74
+ } catch (error) {
75
+ return {
76
+ success: false,
77
+ message: "Failed to find ${name.toLowerCase()}",
78
+ error,
79
+ value: null
80
+ }
53
81
  }
54
82
  }
55
83
 
56
- async update({ id }: ${name}Id, data: Update${name}): Promise<${name}Response<${pluralName} | null>> {
57
- const collection = await this.connect()
58
-
59
- const result = await collection.findOneAndUpdate(
60
- { _id: new ObjectId(id) },
61
- {
62
- $set: {
63
- ...data,
64
- updatedAt: new Date()
65
- }
66
- },
67
- { returnDocument: 'after' }
68
- )
69
-
70
- return {
71
- success: true,
72
- message: result ? "${name} updated successfully" : "${name} not found",
73
- value: result as ${pluralName} | null
84
+ async update({ id }: Readonly<${name}Id>, data: Readonly<Update${name}>): Promise<${name}Response<${pluralName} | null>> {
85
+ try {
86
+ const collection = await this.getCollection()
87
+
88
+ const result = await collection.findOneAndUpdate(
89
+ { _id: new ObjectId(id) },
90
+ {
91
+ $set: {
92
+ ...data,
93
+ updatedAt: new Date()
94
+ }
95
+ },
96
+ { returnDocument: 'after' }
97
+ )
98
+
99
+ return {
100
+ success: true,
101
+ message: result ? "${name} updated successfully" : "${name} not found",
102
+ value: result ? new ${name}(result) as ${pluralName} : null
103
+ }
104
+ } catch (error) {
105
+ return {
106
+ success: false,
107
+ message: "Failed to update ${name.toLowerCase()}",
108
+ error,
109
+ value: null
110
+ }
74
111
  }
75
112
  }
76
113
 
77
114
  async delete({ id }: ${name}Id): Promise<${name}Response<${pluralName} | null>> {
78
- const collection = await this.connect()
115
+ const collection = await this.getCollection()
79
116
 
80
117
  const doc = await collection.findOne({ _id: new ObjectId(id) })
81
118
  if (!doc) {
@@ -90,12 +127,164 @@ export class ${name} {
90
127
  return {
91
128
  success: true,
92
129
  message: "${name} deleted successfully",
93
- value: doc as ${pluralName}
130
+ value: new ${name}(doc) as ${pluralName}
131
+ }
132
+ }
133
+ }
134
+
135
+ export const ${name.toLowerCase()} = new ${name}Repository()`;
136
+ // src/database/postgresql/repository.template.js
137
+ var generatePostgresRepository = (name, pluralName) => `import { getPool } from "../../config"
138
+ import type { Create${name}, Update${name}, ${pluralName}, ${name}Id } from "./${name.toLowerCase()}.schema"
139
+ import { ${name} } from "./${name.toLowerCase()}.schema"
140
+
141
+ type ${name}Response<T> = {
142
+ success: true
143
+ message?: string
144
+ value: T
145
+ } | {
146
+ success: false
147
+ message: string
148
+ error: unknown
149
+ value: null
150
+ }
151
+
152
+ export class ${name}Repository {
153
+ private readonly tableName = "${pluralName.toLowerCase()}"
154
+
155
+ async create(data: Readonly<Create${name}>): Promise<${name}Response<${pluralName}>> {
156
+ try {
157
+ const pool = await getPool()
158
+
159
+ const fields = Object.keys(data)
160
+ const values = Object.values(data)
161
+ const placeholders = values.map((_, i) => \`$\${i + 1}\`).join(', ')
162
+
163
+ const query = \`
164
+ INSERT INTO \${this.tableName}
165
+ (\${fields.join(', ')}, created_at, updated_at)
166
+ VALUES (\${placeholders}, NOW(), NOW())
167
+ RETURNING *
168
+ \`
169
+
170
+ const result = await pool.query(query, values)
171
+ return {
172
+ success: true,
173
+ message: "${name} created successfully",
174
+ value: new ${name}(result.rows[0]) as ${pluralName}
175
+ }
176
+ } catch (error) {
177
+ return {
178
+ success: false,
179
+ message: "Failed to create ${name.toLowerCase()}",
180
+ error,
181
+ value: null
182
+ }
183
+ }
184
+ }
185
+
186
+ async findAll(): Promise<${name}Response<${name}[]>> {
187
+ try {
188
+ const pool = await getPool()
189
+ const result = await pool.query(\`SELECT * FROM \${this.tableName}\`)
190
+
191
+ return {
192
+ success: true,
193
+ value: result.rows.map(row => new ${name}(row))
194
+ }
195
+ } catch (error) {
196
+ return {
197
+ success: false,
198
+ message: "Failed to fetch ${pluralName.toLowerCase()}",
199
+ error,
200
+ value: null
201
+ }
202
+ }
203
+ }
204
+
205
+ async findById({ id }: Readonly<${name}Id>): Promise<${name}Response<${name} | null>> {
206
+ try {
207
+ const pool = await getPool()
208
+ const result = await pool.query(
209
+ \`SELECT * FROM \${this.tableName} WHERE id = $1\`,
210
+ [id]
211
+ )
212
+
213
+ return {
214
+ success: true,
215
+ value: result.rows[0] ? new ${name}(result.rows[0]) : null
216
+ }
217
+ } catch (error) {
218
+ return {
219
+ success: false,
220
+ message: "Failed to find ${name.toLowerCase()}",
221
+ error,
222
+ value: null
223
+ }
224
+ }
225
+ }
226
+
227
+ async update({ id }: Readonly<${name}Id>, data: Readonly<Update${name}>): Promise<${name}Response<${pluralName} | null>> {
228
+ try {
229
+ const pool = await getPool()
230
+
231
+ const fields = Object.keys(data)
232
+ const values = Object.values(data)
233
+ const setClause = fields
234
+ .map((field, i) => \`\${field} = $\${i + 1}\`)
235
+ .join(', ')
236
+
237
+ const query = \`
238
+ UPDATE \${this.tableName}
239
+ SET \${setClause}, updated_at = NOW()
240
+ WHERE id = $\${values.length + 1}
241
+ RETURNING *
242
+ \`
243
+
244
+ const result = await pool.query(query, [...values, id])
245
+
246
+ return {
247
+ success: true,
248
+ message: result.rows[0] ? "${name} updated successfully" : "${name} not found",
249
+ value: result.rows[0] ? new ${name}(result.rows[0]) as ${pluralName} : null
250
+ }
251
+ } catch (error) {
252
+ return {
253
+ success: false,
254
+ message: "Failed to update ${name.toLowerCase()}",
255
+ error,
256
+ value: null
257
+ }
258
+ }
259
+ }
260
+
261
+ async delete({ id }: ${name}Id): Promise<${name}Response<${pluralName} | null>> {
262
+ try {
263
+ const pool = await getPool()
264
+
265
+ const result = await pool.query(
266
+ \`DELETE FROM \${this.tableName} WHERE id = $1 RETURNING *\`,
267
+ [id]
268
+ )
269
+
270
+ return {
271
+ success: true,
272
+ message: result.rows[0] ? "${name} deleted successfully" : "${name} not found",
273
+ value: result.rows[0] ? new ${name}(result.rows[0]) as ${pluralName} : null
274
+ }
275
+ } catch (error) {
276
+ return {
277
+ success: false,
278
+ message: "Failed to delete ${name.toLowerCase()}",
279
+ error,
280
+ value: null
281
+ }
94
282
  }
95
283
  }
96
284
  }
97
285
 
98
- export const ${name.toLowerCase()} = new ${name}()`;
286
+ export const ${name.toLowerCase()} = new ${name}Repository()`;
99
287
  export {
288
+ generatePostgresRepository,
100
289
  generateMongoRepository
101
290
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kontas-express",
3
- "version": "1.0.8",
3
+ "version": "1.0.10",
4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "build": "bun build ./index.js --outdir ./dist --target bun",