mongo-type-safe 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Marko Scekic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # mongo-type-safe
2
+
3
+ A type-safe MongoDB wrapper for Node.js using Zod schemas and TypeScript. Get compile-time safety for all your MongoDB CRUD operations, with a familiar API and zero runtime overhead.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - **Type-safe CRUD**: Compile-time type checking for all MongoDB operations
10
+ - **Zod integration**: Use your Zod schemas as the single source of truth
11
+ - **No runtime validation**: Pure TypeScript safety, no extra checks in production
12
+ - **Familiar API**: Mirrors the official MongoDB Node.js driver
13
+
14
+ ---
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install mongo-type-safe zod mongodb
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Quick Start
25
+
26
+ ### 1. Recommended: Initialize db before importing models (Mongoose-like pattern)
27
+
28
+ **db.ts**
29
+
30
+ ```typescript
31
+ import { MongoClient } from "mongodb";
32
+ export const client = new MongoClient("mongodb://localhost:27017");
33
+ ```
34
+
35
+ **index.ts (entrypoint of your app)**
36
+
37
+ ```typescript
38
+ import { client } from "./db";
39
+ await client.connect(); // Ensure connection before importing models
40
+ export const db = client.db("test-db");
41
+
42
+ // ...rest of your app
43
+ ```
44
+
45
+ **userModel.ts**
46
+
47
+ ```typescript
48
+ import { z } from "zod";
49
+ import { createSafeCollection } from "mongo-type-safe";
50
+ import { db } from "./index"; // or "./db" if you export db there
51
+
52
+ export const userSchema = z.object({
53
+ name: z.string(),
54
+ age: z.number().optional(),
55
+ email: z.string().email()
56
+ });
57
+
58
+ export const safeUsers = createSafeCollection(db.collection("users"), userSchema);
59
+ ```
60
+
61
+ **Anywhere in your app:**
62
+
63
+ ```typescript
64
+ import { safeUsers } from "./userModel";
65
+
66
+ await safeUsers.insertOne({ name: "Marko", email: "marko@example.com" });
67
+ const user = await safeUsers.findOne({ name: "Marko" });
68
+ ```
69
+
70
+ > **Note:** This pattern ensures that your models always have a ready-to-use, type-safe collection. Just make sure the db connection is established before any model is imported.
71
+
72
+ ---
73
+
74
+ ### 2. Model-only approach (if you want to create the collection on demand)
75
+
76
+ **userModel.ts**
77
+
78
+ ```typescript
79
+ import { z } from "zod";
80
+
81
+ export const userSchema = z.object({
82
+ name: z.string(),
83
+ age: z.number().optional(),
84
+ email: z.string().email()
85
+ });
86
+ ```
87
+
88
+ **In your route/service/handler:**
89
+
90
+ ```typescript
91
+ import { MongoClient } from "mongodb";
92
+ import { createSafeCollection } from "mongo-type-safe";
93
+ import { userSchema } from "./userModel";
94
+
95
+ async function main() {
96
+ const client = new MongoClient("mongodb://localhost:27017");
97
+ await client.connect();
98
+ const db = client.db("test-db");
99
+
100
+ // Create the type-safe collection on demand
101
+ const safeUsers = createSafeCollection(db.collection("users"), userSchema);
102
+
103
+ await safeUsers.insertOne({ name: "Marko", email: "marko@example.com" });
104
+ const user = await safeUsers.findOne({ name: "Marko" });
105
+ await safeUsers.updateOne({ name: "Marko" }, { $set: { age: 30 } });
106
+ await safeUsers.deleteOne({ name: "Marko" });
107
+
108
+ client.close();
109
+ }
110
+
111
+ main();
112
+ ```
113
+
114
+ ---
115
+
116
+ ### 3. Model exports ready-to-use collection (if you have a global db instance)
117
+
118
+ **userModel.ts**
119
+
120
+ ```typescript
121
+ import { z } from "zod";
122
+ import { createSafeCollection } from "mongo-type-safe";
123
+ import { db } from "./db"; // your global db instance
124
+
125
+ export const userSchema = z.object({
126
+ name: z.string(),
127
+ age: z.number().optional(),
128
+ email: z.string().email()
129
+ });
130
+
131
+ export const safeUsers = createSafeCollection(db.collection("users"), userSchema);
132
+ ```
133
+
134
+ **Anywhere in your app:**
135
+
136
+ ```typescript
137
+ import { safeUsers } from "./userModel";
138
+
139
+ await safeUsers.insertOne({ name: "Marko", email: "marko@example.com" });
140
+ const user = await safeUsers.findOne({ name: "Marko" });
141
+ ```
142
+
143
+ ---
144
+
145
+ ## API Overview
146
+
147
+ All methods are type-safe and mirror the MongoDB driver:
148
+
149
+ - `insertOne(doc, options?)`
150
+ - `insertMany(docs, options?)`
151
+ - `findOne(filter, options?)`
152
+ - `find(filter, options?)`
153
+ - `updateOne(filter, update, options?)`
154
+ - `updateMany(filter, update, options?)`
155
+ - `deleteOne(filter, options?)`
156
+ - `deleteMany(filter, options?)`
157
+ - `replaceOne(filter, newDocument, options?)`
158
+ - `findOneAndUpdate(filter, update, options?)`
159
+ - `findOneAndReplace(filter, newDocument, options?)`
160
+ - `findOneAndDelete(filter, options?)`
161
+ - `countDocuments(filter?, options?)`
162
+ - `estimatedDocumentCount(options?)`
163
+ - `distinct(key, filter?)`
164
+ - `aggregate(pipeline, options?)`
165
+
166
+ See the source for full method signatures and JSDoc documentation.
167
+
168
+ ---
169
+
170
+ ## Type Safety
171
+
172
+ - All filters, updates, and documents are checked at compile time against your Zod schema.
173
+ - Invalid field names or types will cause TypeScript errors before you run your code.
174
+ - No runtime validation is performed—this is pure TypeScript safety.
175
+
176
+ ---
177
+
178
+ ## Zod Integration
179
+
180
+ - Use your Zod schemas to define the shape of your documents.
181
+ - The wrapper automatically infers TypeScript types from your Zod schema.
182
+
183
+ ---
184
+
185
+ ## License
186
+
187
+ MIT
package/dist/index.js ADDED
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSafeCollection = createSafeCollection;
4
+ const validate_1 = require("./util/validate");
5
+ function createSafeCollection(collection, schema) {
6
+ return {
7
+ /**
8
+ * Inserts a single document into the collection.
9
+ */
10
+ insertOne(doc, options) {
11
+ (0, validate_1.validateOrThrow)(schema, doc);
12
+ return collection.insertOne(doc, options);
13
+ },
14
+ /**
15
+ * Inserts multiple documents into the collection.
16
+ */
17
+ insertMany(docs) {
18
+ docs.forEach(doc => (0, validate_1.validateOrThrow)(schema, doc));
19
+ return collection.insertMany(docs);
20
+ },
21
+ /**
22
+ * Updates a single document matching the filter.
23
+ */
24
+ updateOne(filter, update, options) {
25
+ (0, validate_1.validateFilter)(filter, schema);
26
+ return collection.updateOne(filter, update, options);
27
+ },
28
+ /**
29
+ * Updates a single document matching the filter and returns it (before or after update).
30
+ */
31
+ findOneAndUpdate(filter, update, options) {
32
+ (0, validate_1.validateFilter)(filter, schema);
33
+ return options
34
+ ? collection.findOneAndUpdate(filter, update, options)
35
+ : collection.findOneAndUpdate(filter, update);
36
+ },
37
+ /**
38
+ * Updates multiple documents matching the filter.
39
+ */
40
+ updateMany(filter, update, options) {
41
+ (0, validate_1.validateFilter)(filter, schema);
42
+ return collection.updateMany(filter, update, options);
43
+ },
44
+ /**
45
+ * Finds a single document matching the filter.
46
+ */
47
+ findOne(filter, options) {
48
+ (0, validate_1.validateFilter)(filter, schema);
49
+ return collection.findOne(filter, options);
50
+ },
51
+ /**
52
+ * Finds all documents matching the filter.
53
+ */
54
+ find(filter, options) {
55
+ (0, validate_1.validateFilter)(filter, schema);
56
+ return collection.find(filter, options);
57
+ },
58
+ /**
59
+ * Deletes a single document matching the filter.
60
+ */
61
+ deleteOne(filter, options) {
62
+ (0, validate_1.validateFilter)(filter, schema);
63
+ return collection.deleteOne(filter, options);
64
+ },
65
+ /**
66
+ * Deletes multiple documents matching the filter.
67
+ */
68
+ deleteMany(filter, options) {
69
+ (0, validate_1.validateFilter)(filter, schema);
70
+ return collection.deleteMany(filter, options);
71
+ },
72
+ /**
73
+ * Deletes a single document matching the filter and returns it.
74
+ */
75
+ findOneAndDelete(filter, options) {
76
+ (0, validate_1.validateFilter)(filter, schema);
77
+ return options
78
+ ? collection.findOneAndDelete(filter, options)
79
+ : collection.findOneAndDelete(filter);
80
+ },
81
+ /**
82
+ * Replaces a single document matching the filter with a new document.
83
+ */
84
+ replaceOne(filter, newDocument, options) {
85
+ (0, validate_1.validateFilter)(filter, schema);
86
+ (0, validate_1.validateOrThrow)(schema, newDocument);
87
+ return collection.replaceOne(filter, newDocument, options);
88
+ },
89
+ /**
90
+ * Finds a single document matching the filter, replaces it with a new document, and returns it.
91
+ */
92
+ findOneAndReplace(filter, newDocument, options) {
93
+ (0, validate_1.validateFilter)(filter, schema);
94
+ (0, validate_1.validateOrThrow)(schema, newDocument);
95
+ return options
96
+ ? collection.findOneAndReplace(filter, newDocument, options)
97
+ : collection.findOneAndReplace(filter, newDocument);
98
+ },
99
+ /**
100
+ * Runs an aggregation pipeline on the collection.
101
+ * @template TResult The expected result type of the aggregation.
102
+ */
103
+ aggregate(pipeline, options) {
104
+ return collection.aggregate(pipeline, options);
105
+ },
106
+ /**
107
+ * Counts the number of documents matching the filter.
108
+ */
109
+ countDocuments(filter, options) {
110
+ if (filter)
111
+ (0, validate_1.validateFilter)(filter, schema);
112
+ return collection.countDocuments(filter, options);
113
+ },
114
+ /**
115
+ * Returns the estimated number of documents in the collection.
116
+ */
117
+ estimatedDocumentCount(options) {
118
+ return collection.estimatedDocumentCount(options);
119
+ },
120
+ /**
121
+ * Returns an array of distinct values for the given field across a single collection.
122
+ */
123
+ distinct(key, filter) {
124
+ if (!(key in schema.shape)) {
125
+ throw new Error(`Invalid field: ${String(key)}`);
126
+ }
127
+ if (filter)
128
+ (0, validate_1.validateFilter)(filter, schema);
129
+ return filter
130
+ ? collection.distinct(key, filter)
131
+ : collection.distinct(key);
132
+ }
133
+ };
134
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatZodErrors = formatZodErrors;
4
+ exports.createFilterSchema = createFilterSchema;
5
+ function formatZodErrors(issues) {
6
+ return issues
7
+ .map(issue => `Error at field - ${issue.path.join(".")}: ${issue.message}`)
8
+ .join("\n");
9
+ }
10
+ function createFilterSchema(schema) {
11
+ return schema.partial();
12
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateOrThrow = validateOrThrow;
4
+ exports.validateFilter = validateFilter;
5
+ const zod_1 = require("zod");
6
+ const helper_1 = require("./helper");
7
+ function validateOrThrow(schema, data) {
8
+ try {
9
+ return schema.parse(data);
10
+ }
11
+ catch (err) {
12
+ if (err instanceof zod_1.ZodError) {
13
+ const message = (0, helper_1.formatZodErrors)(err.issues);
14
+ throw new Error(message);
15
+ }
16
+ throw err;
17
+ }
18
+ }
19
+ function validateFilter(filter, schema) {
20
+ const filterSchema = (0, helper_1.createFilterSchema)(schema);
21
+ const parsed = filterSchema.safeParse(filter);
22
+ if (!parsed.success) {
23
+ throw new Error("Invalid filter: " + parsed.error.message);
24
+ }
25
+ return filter;
26
+ }
Binary file
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "mongo-type-safe",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "build": "tsc"
9
+ },
10
+ "keywords": [],
11
+ "author": "Marko Scekic",
12
+ "license": "MIT",
13
+ "description": "Type-safe wrapper around MongoDB collections using Zod validation.",
14
+ "dependencies": {
15
+ "mongodb": "^6.17.0",
16
+ "zod": "^3.25.75"
17
+ },
18
+ "devDependencies": {
19
+ "@types/jest": "^30.0.0",
20
+ "@types/node": "^24.0.10",
21
+ "jest": "^30.0.5",
22
+ "ts-jest": "^29.4.0",
23
+ "ts-node": "^10.9.2",
24
+ "typescript": "^5.8.3"
25
+ }
26
+ }