core-nails 1.0.1 → 1.0.4

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.
@@ -13,10 +13,11 @@ export async function generateModel(modelName) {
13
13
  // Pluralize collection name
14
14
  const collectionName = pluralize(modelName.charAt(0).toLowerCase() + modelName.slice(1));
15
15
  // Boilerplate content for model
16
- const modelContent = `import CreateService from "../concerns/CreateService";
16
+ const modelContent = `import FirebaseAdmin from "@lib/FirebaseAdmin";
17
+ import Nails from "core-nails";
17
18
  import { ${modelName}Schema } from "@schema";
18
19
 
19
- const ${modelName} = CreateService({
20
+ const ${modelName} = Nails.InitializeModel({
20
21
  collection: "${collectionName}",
21
22
  schema: ${modelName}Schema,
22
23
  });
@@ -0,0 +1,31 @@
1
+ import { z, ZodObject, ZodRawShape } from "zod";
2
+ type WhereOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "array-contains" | "in" | "not-in" | "array-contains-any";
3
+ type WhereCondition<T> = {
4
+ field: keyof T;
5
+ operator: WhereOperator;
6
+ value: any;
7
+ };
8
+ declare function InitializeModel<TSchema extends ZodObject<ZodRawShape>>(opts: {
9
+ collection: string;
10
+ schema: TSchema;
11
+ FirebaseAdmin: any;
12
+ }): {
13
+ all(): Promise<(z.core.output<TSchema> & {
14
+ id: string;
15
+ })[]>;
16
+ find(id: string): Promise<(z.core.output<TSchema> & {
17
+ id: string;
18
+ }) | null>;
19
+ create(data: z.core.output<TSchema>, id?: string): Promise<(z.core.output<TSchema> & {
20
+ id: string;
21
+ }) | null>;
22
+ update(data: Partial<z.core.output<TSchema>>, id: string): Promise<void>;
23
+ destroy(id: string): Promise<void>;
24
+ where(conditions: WhereCondition<z.core.output<TSchema>>[]): Promise<(z.core.output<TSchema> & {
25
+ id: string;
26
+ })[]>;
27
+ find_by(conditions: WhereCondition<z.core.output<TSchema>>[]): Promise<(z.core.output<TSchema> & {
28
+ id: string;
29
+ }) | null>;
30
+ };
31
+ export default InitializeModel;
@@ -0,0 +1,95 @@
1
+ function InitializeModel(opts) {
2
+ const { collection: collectionName, schema, FirebaseAdmin } = opts;
3
+ const db = FirebaseAdmin.firestore();
4
+ const collection = db.collection(collectionName);
5
+ function parseDoc(doc) {
6
+ if (!doc.exists)
7
+ return null;
8
+ const result = schema.safeParse(doc.data());
9
+ if (!result.success || typeof result.data !== "object" || result.data === null)
10
+ return null;
11
+ return {
12
+ id: doc.id,
13
+ ...result.data,
14
+ };
15
+ }
16
+ function parseDocs(snapshot) {
17
+ return snapshot.docs
18
+ .map(parseDoc)
19
+ .filter((doc) => doc !== null);
20
+ }
21
+ return {
22
+ async all() {
23
+ const snapshot = await collection.get();
24
+ return parseDocs(snapshot);
25
+ },
26
+ async find(id) {
27
+ const snapshot = await collection.doc(id).get();
28
+ return parseDoc(snapshot);
29
+ },
30
+ async create(data, id) {
31
+ const dataWithTimestamp = {
32
+ ...data,
33
+ createdAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
34
+ updatedAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
35
+ };
36
+ const parsed = schema.parse(dataWithTimestamp);
37
+ let docRef;
38
+ if (id) {
39
+ docRef = collection.doc(id);
40
+ const existingDoc = await docRef.get();
41
+ if (existingDoc.exists) {
42
+ throw new Error(`Document with ID ${id} already exists!`);
43
+ }
44
+ await docRef.set(parsed);
45
+ }
46
+ else {
47
+ docRef = await collection.add(parsed);
48
+ }
49
+ const docSnap = await docRef.get();
50
+ if (!docSnap.exists)
51
+ return null;
52
+ const result = schema.safeParse(docSnap.data());
53
+ if (!result.success || typeof result.data !== "object" || result.data === null)
54
+ return null;
55
+ return {
56
+ id: docSnap.id,
57
+ ...result.data,
58
+ };
59
+ },
60
+ async update(data, id) {
61
+ if ("createdAt" in data) {
62
+ throw new Error("Cannot modify createdAt field");
63
+ }
64
+ const dataWithTimestamp = {
65
+ ...data,
66
+ updatedAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
67
+ };
68
+ const partialSchema = schema.partial();
69
+ const parsed = partialSchema.parse(dataWithTimestamp);
70
+ await collection.doc(id).update(parsed);
71
+ },
72
+ async destroy(id) {
73
+ await collection.doc(id).delete();
74
+ },
75
+ async where(conditions) {
76
+ let query = collection;
77
+ for (const cond of conditions) {
78
+ query = query.where(cond.field, cond.operator, cond.value);
79
+ }
80
+ const snapshot = await query.get();
81
+ return parseDocs(snapshot);
82
+ },
83
+ async find_by(conditions) {
84
+ let query = collection;
85
+ for (const cond of conditions) {
86
+ query = query.where(cond.field, cond.operator, cond.value);
87
+ }
88
+ const snapshot = await query.limit(1).get();
89
+ if (snapshot.empty)
90
+ return null;
91
+ return parseDoc(snapshot.docs[0]);
92
+ },
93
+ };
94
+ }
95
+ export default InitializeModel;
@@ -0,0 +1,5 @@
1
+ import InitializeModel from "./helpers/InitializeModel.js";
2
+ declare const _default: {
3
+ InitializeModel: typeof InitializeModel;
4
+ };
5
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import InitializeModel from "./helpers/InitializeModel.js";
2
+ export default { InitializeModel };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "core-nails",
3
- "version": "1.0.1",
3
+ "version": "1.0.4",
4
4
  "scripts": {
5
5
  "build": "tsc"
6
6
  },
@@ -13,6 +13,10 @@
13
13
  "typescript": "^6.0.2"
14
14
  },
15
15
  "dependencies": {
16
- "pluralize": "^8.0.0"
16
+ "pluralize": "^8.0.0",
17
+ "zod": "^4.3.6"
18
+ },
19
+ "exports": {
20
+ ".": "./dist/index.js"
17
21
  }
18
22
  }
@@ -19,10 +19,11 @@ export async function generateModel(modelName: string) {
19
19
  );
20
20
 
21
21
  // Boilerplate content for model
22
- const modelContent = `import CreateService from "../concerns/CreateService";
22
+ const modelContent = `import FirebaseAdmin from "@lib/FirebaseAdmin";
23
+ import Nails from "core-nails";
23
24
  import { ${modelName}Schema } from "@schema";
24
25
 
25
- const ${modelName} = CreateService({
26
+ const ${modelName} = Nails.InitializeModel({
26
27
  collection: "${collectionName}",
27
28
  schema: ${modelName}Schema,
28
29
  });
@@ -0,0 +1,161 @@
1
+ import { z, ZodObject, ZodRawShape } from "zod";
2
+
3
+ type WhereOperator =
4
+ | "=="
5
+ | "!="
6
+ | "<"
7
+ | "<="
8
+ | ">"
9
+ | ">="
10
+ | "array-contains"
11
+ | "in"
12
+ | "not-in"
13
+ | "array-contains-any";
14
+
15
+ type WhereCondition<T> = {
16
+ field: keyof T;
17
+ operator: WhereOperator;
18
+ value: any;
19
+ };
20
+
21
+ function InitializeModel<TSchema extends ZodObject<ZodRawShape>>(opts: {
22
+ collection: string;
23
+ schema: TSchema;
24
+ FirebaseAdmin: any;
25
+ }) {
26
+ const { collection: collectionName, schema, FirebaseAdmin } = opts;
27
+
28
+ type T = z.infer<TSchema>;
29
+ type WithId = T & { id: string };
30
+
31
+ const db = FirebaseAdmin.firestore();
32
+ const collection = db.collection(collectionName);
33
+
34
+ function parseDoc(doc: any): WithId | null {
35
+ if (!doc.exists) return null;
36
+
37
+ const result = schema.safeParse(doc.data());
38
+
39
+ if (!result.success || typeof result.data !== "object" || result.data === null) return null;
40
+
41
+ return {
42
+ id: doc.id,
43
+ ...result.data,
44
+ };
45
+ }
46
+
47
+ function parseDocs(
48
+ snapshot: any
49
+ ): WithId[] {
50
+ return snapshot.docs
51
+ .map(parseDoc)
52
+ .filter((doc: WithId | null): doc is WithId => doc !== null);
53
+ }
54
+
55
+ return {
56
+ async all(): Promise<WithId[]> {
57
+ const snapshot = await collection.get();
58
+ return parseDocs(snapshot);
59
+ },
60
+
61
+ async find(id: string): Promise<WithId | null> {
62
+ const snapshot = await collection.doc(id).get();
63
+ return parseDoc(snapshot);
64
+ },
65
+
66
+ async create(data: T, id?: string): Promise<WithId | null> {
67
+ const dataWithTimestamp = {
68
+ ...data,
69
+ createdAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
70
+ updatedAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
71
+ };
72
+
73
+ const parsed = schema.parse(dataWithTimestamp) as any;
74
+
75
+ let docRef: any;
76
+
77
+ if (id) {
78
+ docRef = collection.doc(id);
79
+
80
+ const existingDoc = await docRef.get();
81
+ if (existingDoc.exists) {
82
+ throw new Error(`Document with ID ${id} already exists!`);
83
+ }
84
+
85
+ await docRef.set(parsed);
86
+ } else {
87
+ docRef = await collection.add(parsed);
88
+ }
89
+
90
+ const docSnap = await docRef.get();
91
+ if (!docSnap.exists) return null;
92
+
93
+ const result = schema.safeParse(docSnap.data());
94
+ if (!result.success || typeof result.data !== "object" || result.data === null) return null;
95
+
96
+ return {
97
+ id: docSnap.id,
98
+ ...result.data,
99
+ };
100
+ },
101
+
102
+ async update(data: Partial<T>, id: string): Promise<void> {
103
+ if ("createdAt" in data) {
104
+ throw new Error("Cannot modify createdAt field");
105
+ }
106
+
107
+ const dataWithTimestamp = {
108
+ ...data,
109
+ updatedAt: FirebaseAdmin.firestore.FieldValue.serverTimestamp(),
110
+ };
111
+
112
+ const partialSchema = schema.partial();
113
+ const parsed = partialSchema.parse(dataWithTimestamp);
114
+
115
+ await collection.doc(id).update(parsed);
116
+ },
117
+
118
+ async destroy(id: string): Promise<void> {
119
+ await collection.doc(id).delete();
120
+ },
121
+
122
+ async where(
123
+ conditions: WhereCondition<T>[]
124
+ ): Promise<WithId[]> {
125
+ let query: any = collection;
126
+
127
+ for (const cond of conditions) {
128
+ query = query.where(
129
+ cond.field as string,
130
+ cond.operator,
131
+ cond.value
132
+ );
133
+ }
134
+
135
+ const snapshot = await query.get();
136
+ return parseDocs(snapshot);
137
+ },
138
+
139
+ async find_by(
140
+ conditions: WhereCondition<T>[]
141
+ ): Promise<WithId | null> {
142
+ let query: any = collection;
143
+
144
+ for (const cond of conditions) {
145
+ query = query.where(
146
+ cond.field as string,
147
+ cond.operator,
148
+ cond.value
149
+ );
150
+ }
151
+
152
+ const snapshot = await query.limit(1).get();
153
+
154
+ if (snapshot.empty) return null;
155
+
156
+ return parseDoc(snapshot.docs[0]);
157
+ },
158
+ };
159
+ }
160
+
161
+ export default InitializeModel;
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ import InitializeModel from "./helpers/InitializeModel.js";
2
+
3
+ export default { InitializeModel };
@@ -1 +0,0 @@
1
- export declare function runGenerate(args: string[]): Promise<void>;
@@ -1,23 +0,0 @@
1
- export async function runGenerate(args) {
2
- const [type, name] = args;
3
- if (!type || !name) {
4
- console.error("Usage: nails generate <type> <name>");
5
- process.exit(1);
6
- }
7
- switch (type) {
8
- case "model": {
9
- const { generateModel } = await import("./model.js");
10
- await generateModel(name);
11
- break;
12
- }
13
- case "scaffold": {
14
- const { generateScaffold } = await import("./scaffold.js");
15
- await generateScaffold(name);
16
- break;
17
- }
18
- default: {
19
- console.error(`Unknown generator: ${type}`);
20
- process.exit(1);
21
- }
22
- }
23
- }
@@ -1 +0,0 @@
1
- export declare function generateModel(modelName: string): Promise<void>;
@@ -1,61 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import pluralize from "pluralize";
4
- export async function generateModel(modelName) {
5
- if (!modelName) {
6
- console.error("Usage: yarn generate model <ModelName>");
7
- console.error("Example: yarn generate model UserActivity");
8
- process.exit(1);
9
- }
10
- // Convert model name to match filename conventions
11
- const dirName = path.join("app", "(model)", modelName);
12
- const filePath = path.join(dirName, "index.ts");
13
- // Pluralize collection name
14
- const collectionName = pluralize(modelName.charAt(0).toLowerCase() + modelName.slice(1));
15
- // Boilerplate content for model
16
- const modelContent = `import CreateService from "../concerns/CreateService";
17
- import { ${modelName}Schema } from "@schema";
18
-
19
- const ${modelName} = CreateService({
20
- collection: "${collectionName}",
21
- schema: ${modelName}Schema,
22
- });
23
-
24
- export default ${modelName};
25
- `;
26
- // Create model directory and write index.ts
27
- fs.mkdirSync(dirName, { recursive: true });
28
- fs.writeFileSync(filePath, modelContent);
29
- console.log(`create ${path.relative(process.cwd(), filePath)}`);
30
- // --- Append schema stub to db/schema.ts ---
31
- const dbDir = path.join("db");
32
- fs.mkdirSync(dbDir, { recursive: true });
33
- const schemaFilePath = path.join(dbDir, "schema.ts");
34
- const schemaBaseContent = `import FirebaseAdmin from "@lib/FirebaseAdmin";
35
- import { z } from "zod";
36
-
37
- // Helper Function
38
- const FirebaseTimestamp = z.union([
39
- z.instanceof(FirebaseAdmin.firestore.Timestamp),
40
- z.date(),
41
- z.custom((val) => val === FirebaseAdmin.firestore.FieldValue.serverTimestamp(), { message: "Expected serverTimestamp()" }),
42
- ]);
43
- `;
44
- // Ensure schema file exists
45
- if (!fs.existsSync(schemaFilePath)) {
46
- fs.writeFileSync(schemaFilePath, schemaBaseContent);
47
- console.log(`create ${path.relative(process.cwd(), schemaFilePath)}`);
48
- }
49
- else {
50
- console.log(`append ${path.relative(process.cwd(), schemaFilePath)}`);
51
- }
52
- const schemaStub = `
53
- // ${modelName} Schema
54
- export const ${modelName}Schema = z.object({
55
- createdAt: FirebaseTimestamp.optional(),
56
- updatedAt: FirebaseTimestamp.optional(),
57
- });
58
- export type ${modelName}Type = z.infer<typeof ${modelName}Schema>;
59
- `;
60
- fs.appendFileSync(schemaFilePath, schemaStub);
61
- }
@@ -1 +0,0 @@
1
- export declare function generateScaffold(scaffoldName: string): Promise<void>;
@@ -1,105 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import pluralize from "pluralize";
4
- import { generateModel } from "./model.js";
5
- export async function generateScaffold(scaffoldName) {
6
- if (!scaffoldName) {
7
- console.error("Usage: yarn generate scaffold <ScaffoldName>");
8
- console.error("Example: yarn generate scaffold UserActivity");
9
- process.exit(1);
10
- }
11
- function toSnakeCase(name) {
12
- const snake = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
13
- return pluralize(snake);
14
- }
15
- const camelName = scaffoldName.charAt(0).toUpperCase() + scaffoldName.slice(1);
16
- const snakePluralName = toSnakeCase(scaffoldName);
17
- // --- 1️⃣ Generate Model (if missing) ---
18
- const modelDir = path.join("app", "(model)", camelName);
19
- if (!fs.existsSync(modelDir)) {
20
- console.log(`Model not found for ${camelName}, generating...`);
21
- await generateModel(scaffoldName);
22
- }
23
- // --- 2️⃣ Paths ---
24
- const controllerDir = path.join("app", "(controller)", camelName);
25
- const apiDir = path.join("app", "api", snakePluralName);
26
- const apiIdDir = path.join(apiDir, "[id]");
27
- // --- 3️⃣ Action files ---
28
- const actions = ["index", "show", "create", "update", "destroy"];
29
- fs.mkdirSync(controllerDir, { recursive: true });
30
- const actionsDir = path.join(controllerDir, "actions");
31
- fs.mkdirSync(actionsDir, { recursive: true });
32
- actions.forEach((action) => {
33
- const filePath = path.join(actionsDir, `${action}_action.ts`);
34
- const content = `export default async function ${action}_action(req: Request${["index", "create"].includes(action) ? "" : ", id: string"}) {
35
- return new Response(JSON.stringify({ message: "${action} ${camelName}" }));
36
- }
37
- `;
38
- fs.writeFileSync(filePath, content);
39
- console.log(`create ${path.relative(process.cwd(), filePath)}`);
40
- });
41
- // --- 4️⃣ controller index.ts ---
42
- const indexContent = actions
43
- .map((action) => `import ${action}_action from "./actions/${action}_action";`)
44
- .join("\n") +
45
- `
46
-
47
- export default {
48
- ${actions.map((a) => ` ${a}_action,`).join("\n")}
49
- };
50
- `;
51
- const controllerIndexPath = path.join(controllerDir, "index.ts");
52
- fs.writeFileSync(controllerIndexPath, indexContent);
53
- console.log(`create ${path.relative(process.cwd(), controllerIndexPath)}`);
54
- // --- 5️⃣ API route.ts ---
55
- fs.mkdirSync(apiDir, { recursive: true });
56
- const apiRoutePath = path.join(apiDir, "route.ts");
57
- const apiRouteContent = `/**
58
- * Standard RESTful Routes
59
- *
60
- * | HTTP Verb | Controller#Action | Purpose | Path |
61
- * |-----------|-------------------|------------------|--------------------------------------------|
62
- * | GET | index | List all | /${snakePluralName}
63
- * | GET | show | Get one | /${snakePluralName}/:id
64
- * | POST | create | Create | /${snakePluralName}
65
- * | PATCH | update | Update (partial) | /${snakePluralName}/:id
66
- * | PUT | update | Update (full) | /${snakePluralName}/:id
67
- * | DELETE | destroy | Delete | /${snakePluralName}/:id
68
- */
69
-
70
- import ${camelName}Controller from "@controller/${camelName}";
71
-
72
- export async function GET(req: Request) {
73
- return ${camelName}Controller.index_action(req);
74
- }
75
-
76
- export async function POST(req: Request) {
77
- return ${camelName}Controller.create_action(req);
78
- }
79
- `;
80
- fs.writeFileSync(apiRoutePath, apiRouteContent);
81
- console.log(`create ${path.relative(process.cwd(), apiRoutePath)}`);
82
- // --- 6️⃣ API [id]/route.ts ---
83
- fs.mkdirSync(apiIdDir, { recursive: true });
84
- const apiIdRoutePath = path.join(apiIdDir, "route.ts");
85
- const apiIdRouteContent = `import ${camelName}Controller from "@controller/${camelName}";
86
-
87
- export async function GET(req: Request, { params }: { params: { id: string } }) {
88
- return ${camelName}Controller.show_action(req, params.id);
89
- }
90
-
91
- export async function PATCH(req: Request, { params }: { params: { id: string } }) {
92
- return ${camelName}Controller.update_action(req, params.id);
93
- }
94
-
95
- export async function PUT(req: Request, { params }: { params: { id: string } }) {
96
- return ${camelName}Controller.update_action(req, params.id);
97
- }
98
-
99
- export async function DELETE(req: Request, { params }: { params: { id: string } }) {
100
- return ${camelName}Controller.destroy_action(req, params.id);
101
- }
102
- `;
103
- fs.writeFileSync(apiIdRoutePath, apiIdRouteContent);
104
- console.log(`create ${path.relative(process.cwd(), apiIdRoutePath)}`);
105
- }
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- declare const command: any, args: any;
3
- declare function run(): Promise<void>;
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- const [, , command, ...args] = process.argv;
4
- async function run() {
5
- switch (command) {
6
- case "generate": {
7
- const { runGenerate } = await import("./generate/index.js");
8
- await runGenerate(args);
9
- break;
10
- }
11
- default: {
12
- console.log(`Unknown command: ${command}`);
13
- console.log("Available commands: generate");
14
- process.exit(1);
15
- }
16
- }
17
- }
18
- run();