lamix 4.2.6

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.
@@ -0,0 +1,93 @@
1
+ const Post = require('../app/models/Post');
2
+ const User = require('../app/models/User');
3
+
4
+ class PostController {
5
+ async index(req, res) {
6
+ try {
7
+ const { page, perPage } = req.query;
8
+ const result = await Post.query().paginate(page || 1, perPage || 10);
9
+ return res.render('posts/index', { posts: result.data, page: result.page, lastPage: result.lastPage });
10
+ } catch (err) {
11
+ console.error(err);
12
+ return res.status(500).send('Error listing posts');
13
+ }
14
+ }
15
+
16
+ async show(req, res) {
17
+ try {
18
+ const { id } = req.params;
19
+ const post = await Post.query().with('user').where('id', id).first();
20
+ if (!post) return res.status(404).send('Post not found');
21
+ return res.render('posts/show', { post });
22
+ } catch (err) {
23
+ console.error(err);
24
+ return res.status(500).send('Error fetching post');
25
+ }
26
+ }
27
+
28
+ async create(req, res) {
29
+ const users = await User.query().get();
30
+ return res.render('posts/create', { users });
31
+ }
32
+
33
+ async store(req, res) {
34
+ try {
35
+ const attrs = req.body;
36
+ const post = await Post.create(attrs);
37
+ return res.redirect(`/posts/${post.id}`);
38
+ } catch (err) {
39
+ console.error(err);
40
+ return res.status(400).send('Error creating post');
41
+ }
42
+ }
43
+
44
+ async edit(req, res) {
45
+ const { id } = req.params;
46
+ const post = await Post.find(id);
47
+ if (!post) return res.status(404).send('Post not found');
48
+ const users = await User.query().get();
49
+ return res.render('posts/edit', { post, users });
50
+ }
51
+
52
+ async update(req, res) {
53
+ try {
54
+ const { id } = req.params;
55
+ const post = await Post.find(id);
56
+ if (!post) return res.status(404).send('Post not found');
57
+ await post.fill(req.body);
58
+ await post.save();
59
+ return res.redirect(`/posts/${post.id}`);
60
+ } catch (err) {
61
+ console.error(err);
62
+ return res.status(400).send('Error updating post');
63
+ }
64
+ }
65
+
66
+ async destroy(req, res) {
67
+ try {
68
+ const { id } = req.params;
69
+ const post = await Post.find(id);
70
+ if (!post) return res.status(404).send('Post not found');
71
+ await post.delete();
72
+ return res.redirect('/posts');
73
+ } catch (err) {
74
+ console.error(err);
75
+ return res.status(500).send('Error deleting post');
76
+ }
77
+ }
78
+
79
+ async restore(req, res) {
80
+ try {
81
+ const { id } = req.params;
82
+ const p = await Post.withTrashed().where('id', id).first();
83
+ if (!p) return res.status(404).send('Post not found');
84
+ await p.restore();
85
+ return res.redirect(`/posts/${p.id}`);
86
+ } catch (err) {
87
+ console.error(err);
88
+ return res.status(500).send('Error restoring post');
89
+ }
90
+ }
91
+ }
92
+
93
+ module.exports = new PostController();
@@ -0,0 +1,55 @@
1
+ const qb = User.query();
2
+
3
+ // Select
4
+ const names = await User.query().select('id', 'name').get();
5
+
6
+ // Aggregates
7
+ const cnt = await User.query().count();
8
+ const sumId = await User.query().sum('id');
9
+ const avgId = await User.query().avg('id');
10
+ const minId = await User.query().min('id');
11
+ const maxId = await User.query().max('id');
12
+
13
+ // Status column example
14
+ const users = await User.query().where('status', true).get();
15
+
16
+ // Ordering
17
+ const usersorderbyid = await User.query()
18
+ .where('status', true)
19
+ .orderBy('id', 'desc')
20
+ .get();
21
+
22
+ // Pluck
23
+ const emails = await User.query().pluck('email');
24
+
25
+ // Pagination
26
+ const page1 = await User.query().paginate(1, 10);
27
+
28
+ // Where In
29
+ const usersIn = await User.query().whereIn('id', [1, 2, 3]).get();
30
+
31
+ // Null checks
32
+ const withNull = await User.query().whereNull('deleted_at').get();
33
+ const notNull = await User.query().whereNotNull('deleted_at').get();
34
+
35
+ // Between
36
+ const inRange = await User.query().whereBetween('id', [10, 20]).get();
37
+
38
+ // Grouping & having
39
+ const grouped = await User.query()
40
+ .select('user_id', 'COUNT(*) as cnt')
41
+ .groupBy('user_id')
42
+ .having('cnt', '>', 1)
43
+ .get();
44
+
45
+ // Joins
46
+ const withPosts = await User.query()
47
+ .select('users.*', 'posts.title as post_title')
48
+ .join('INNER', 'posts', 'users.id', '=', 'posts.user_id')
49
+ .get();
50
+
51
+ // Locking
52
+ await User.query().where('id', 5).forUpdate().get();
53
+
54
+ // Raw queries
55
+ const rows = await User.raw('SELECT * FROM users WHERE id = ?', [5]);
@@ -0,0 +1,16 @@
1
+ // One-to-many
2
+ const user = await User.find(1);
3
+ const posts = await user.posts().get();
4
+
5
+ // Eager loading
6
+ const usersWithPosts = await User.query().with('posts').get();
7
+
8
+ // Many-to-many
9
+ const user = await User.find(2);
10
+
11
+ const roles = await user.roles().get();
12
+ await user.roles().attach(5);
13
+ await user.roles().detach(3);
14
+
15
+ // Eager load multiple relations
16
+ const users = await User.query().with(['roles', 'posts', 'comments']).get();
@@ -0,0 +1,26 @@
1
+ const { BaseModel } = require('lamix');
2
+
3
+ class Role extends BaseModel {
4
+ static table = 'roles';
5
+ static primaryKey = 'id';
6
+ static timestamps = false;
7
+ static softDeletes = false;// Optional if you don't need it
8
+ static fillable = ['name'];
9
+ static rules = {
10
+ name: 'required|string'
11
+ };
12
+
13
+ users() {
14
+ const User = require('./User');
15
+ return this.belongsToMany(
16
+ User,
17
+ 'user_roles',
18
+ 'role_id',
19
+ 'user_id',
20
+ 'id',
21
+ 'id'
22
+ ).onDelete('detach');
23
+ }
24
+ }
25
+
26
+ module.exports = Role;
@@ -0,0 +1,65 @@
1
+ const Role = require('../app/models/Role');
2
+
3
+ class RoleController {
4
+ async index(req, res) {
5
+ const roles = await Role.query().get();
6
+ return res.render('roles/index', { roles });
7
+ }
8
+
9
+ async show(req, res) {
10
+ const { id } = req.params;
11
+ const role = await Role.find(id);
12
+ if (!role) return res.status(404).send('Role not found');
13
+ return res.render('roles/show', { role });
14
+ }
15
+
16
+ async create(req, res) {
17
+ return res.render('roles/create');
18
+ }
19
+
20
+ async store(req, res) {
21
+ try {
22
+ const r = await Role.create(req.body);
23
+ return res.redirect(`/roles/${r.id}`);
24
+ } catch (err) {
25
+ console.error(err);
26
+ return res.status(400).send('Error creating role');
27
+ }
28
+ }
29
+
30
+ async edit(req, res) {
31
+ const { id } = req.params;
32
+ const role = await Role.find(id);
33
+ if (!role) return res.status(404).send('Role not found');
34
+ return res.render('roles/edit', { role });
35
+ }
36
+
37
+ async update(req, res) {
38
+ try {
39
+ const { id } = req.params;
40
+ const role = await Role.find(id);
41
+ if (!role) return res.status(404).send('Role not found');
42
+ await role.fill(req.body);
43
+ await role.save();
44
+ return res.redirect(`/roles/${role.id}`);
45
+ } catch (err) {
46
+ console.error(err);
47
+ return res.status(400).send('Error updating role');
48
+ }
49
+ }
50
+
51
+ async destroy(req, res) {
52
+ try {
53
+ const { id } = req.params;
54
+ const role = await Role.find(id);
55
+ if (!role) return res.status(404).send('Role not found');
56
+ await role.delete();
57
+ return res.redirect('/roles');
58
+ } catch (err) {
59
+ console.error(err);
60
+ return res.status(500).send('Error deleting role');
61
+ }
62
+ }
63
+ }
64
+
65
+ module.exports = new RoleController();
@@ -0,0 +1,132 @@
1
+ //Basic CRUD & Query
2
+
3
+ const User = require('./models/User');
4
+
5
+ // Create new user
6
+ const user = await User.create({ name: 'Alice', email: 'alice@example.com', password: 'secret' });
7
+
8
+ // Fill & save (update)
9
+ user.name = 'Alice Smith'; // you can also use user.fill({ name: 'Alice Smith' })
10
+ await user.save();
11
+
12
+ // Find by primary key
13
+ const user1 = await User.find(1);
14
+ const user2 = await User.findOrFail(param.id);
15
+
16
+ // Query with where
17
+ const someUsers = await User.where('email', 'alice@example.com').get();
18
+
19
+ // First match
20
+ const firstUser = await User.where('name', 'Alice').first();
21
+ const firstOrFail = await User.where('name', 'Alice').firstOrFail();
22
+
23
+ const user = await User.findBy('email', 'jane@example.com');
24
+ // by default Field password is Auto encrypted when creating
25
+ const isValid = await user.checkPassword('user_input_password');
26
+ // Delete (soft delete if enabled)
27
+ await user.delete();
28
+
29
+ // destroy (delete Multiple ids)
30
+ await user.destroy();
31
+
32
+ // update (by default)
33
+ await user.update({ body });
34
+ or
35
+ // update
36
+ await user.fill({ body });
37
+ await user.save();
38
+
39
+ // Restore (if softDeletes enabled)
40
+ await user.restore();
41
+
42
+ // List all (excluding trashed, by default)
43
+ const allUsers = await User.all();
44
+
45
+ // Query including soft-deleted (trashed) records
46
+ const withTrashed = await User.withTrashed().where('id', 1).first();
47
+
48
+ //QueryBuilder Advanced Features
49
+
50
+ const qb = User.query();
51
+
52
+ // Select specific columns
53
+ const names = await User.query().select('id', 'name').get();
54
+
55
+ // Aggregates
56
+ const cnt = await User.query().count(); // count(*)
57
+ const sumId = await User.query().sum('id');
58
+ const avgId = await User.query().avg('id');
59
+ const minId = await User.query().min('id');
60
+ const maxId = await User.query().max('id');
61
+
62
+ // status a column (returns status of boolean values)
63
+ const usersAll = await User.all();
64
+ const users = await User.query().where('status', true).get();
65
+ const usersorderbyid = await User.query().where('status', true).orderBy('id', 'desc').get();
66
+ const usersorderbycreateAt = await User.query().where('status', true).orderBy('created_at', 'desc').get();
67
+
68
+ // Pluck a column (returns array of values)
69
+ const Pluckemails = await User.query().pluck('email');
70
+
71
+ // Pagination
72
+ const page1 = await User.query().paginate(1, 10);
73
+ // page1 = { total, perPage, page, lastPage, data: [users...] }
74
+
75
+ // Where In
76
+ const usersIn = await User.query().whereIn('id', [1, 2, 3]).get();
77
+
78
+ // Where Null / Not Null
79
+ const withNull = await User.query().whereNull('deleted_at').get();
80
+ const notNull = await User.query().whereNotNull('deleted_at').get();
81
+
82
+ // Where Between
83
+ const inRange = await User.query().whereBetween('id', [10, 20]).get();
84
+
85
+ // Ordering, grouping, having
86
+ const grouped = await User.query()
87
+ .select('user_id', 'COUNT(*) as cnt')
88
+ .groupBy('user_id')
89
+ .having('cnt', '>', 1)
90
+ .get();
91
+
92
+ // Joins
93
+ const withPosts = await User.query()
94
+ .select('users.*', 'posts.title as post_title')
95
+ .join('INNER', 'posts', 'users.id', '=', 'posts.user_id')
96
+ .get();
97
+
98
+ // Using “forUpdate” (locking)
99
+ await User.query().where('id', 5).forUpdate().get();
100
+
101
+ // Raw queries
102
+ const rows = await User.raw('SELECT * FROM users WHERE id = ?', [5]);
103
+
104
+ // Caching
105
+ const cachedRows = await User.raw('SELECT * FROM users', []).then(rows => rows);
106
+ const cached = await DB.cached('SELECT * FROM users WHERE id = ?', [5], 60000);
107
+
108
+ //You can use relations:
109
+
110
+ const user = await User.find(1);
111
+ const posts = await user.posts().get(); // all posts for the user
112
+
113
+ // Eager load in a query with Relations:
114
+ const usersWithPosts = await User.query().with('posts').get();
115
+ // Each user will have a `posts` field with array of post models.
116
+
117
+ // Many-to-many example
118
+ // Suppose you have an intermediate pivot table user_roles (user_id, role_id)
119
+ // and models User and Role, with pivot user_roles.
120
+ //
121
+
122
+ // Then:
123
+ const user = await User.find(2);
124
+ const roles = await user.roles().get();
125
+
126
+ // Eager load with Relations:
127
+ const usersWithRoles = await User.query().with('roles').get();
128
+
129
+ // Eager load with Many to Many Relations:
130
+ const usersWith_Roles_posts_comments = await User.query().with(['roles', 'posts', 'comments' ]).get();
131
+ //OR with Many to Many Relations:
132
+ const users_With_Roles_posts_comments = await User.with(['roles', 'posts', 'comments' ]).get();
@@ -0,0 +1,40 @@
1
+ // models/User.js
2
+ const { BaseModel} = require('lamix');
3
+
4
+ class User extends BaseModel {
5
+ static table = 'users';
6
+ static primaryKey = 'id';
7
+ static timestamps = true;
8
+ static softDeletes = true;// Optional if you don't need it
9
+ static fillable = ['name', 'email', 'password'];// password is Auto encrypted when creating.
10
+ static rules = {
11
+ name: 'required|string',
12
+ email: 'required|email|unique:users,email',
13
+ password: 'required|string|min:6',
14
+ phone: 'nullable|phone',
15
+ status: 'nullable|boolean'
16
+ };
17
+
18
+ profile() {
19
+ return this.hasOne(Profile).onDelete('restrict');
20
+ }
21
+
22
+
23
+ // Many-to-many: User ↔ Role via pivot user_roles (user_id, role_id)
24
+ roles() {
25
+ const Role = require('./Role');
26
+ return this.belongsToMany(
27
+ Role,
28
+ 'user_roles',
29
+ 'user_id',
30
+ 'role_id'
31
+ ).onDelete('detach');
32
+ }
33
+
34
+ // One-to-many: User -> Post
35
+ posts() {
36
+ return this.hasMany(require('./Post'), 'user_id', 'id').onDelete('cascade');
37
+ }
38
+ }
39
+
40
+ module.exports = User;
@@ -0,0 +1,98 @@
1
+ // controllers/UserController.js
2
+ const User = require('Model-User');
3
+ const { ValidationError } = require('lamix');
4
+
5
+ class UserController {
6
+ // GET /users
7
+ async index(req, res) {
8
+ try {
9
+ const users = await User.query().get();
10
+ return res.json(users);
11
+ } catch (err) {
12
+ return res.status(500).json({ error: 'Failed to fetch users.' });
13
+ }
14
+ }
15
+
16
+ // GET /users/:id
17
+ async show(req, res) {
18
+ try {
19
+ const user = await User.find(req.params.id);
20
+ if (!user) return res.status(404).json({ error: 'User not found.' });
21
+ return res.json(user);
22
+ } catch (err) {
23
+ return res.status(500).json({ error: 'Failed to fetch user.' });
24
+ }
25
+ }
26
+
27
+ // POST /users
28
+ static async store(req, res) {
29
+ const input = {
30
+ name: req.body.name,
31
+ email: req.body.email,
32
+ password: req.body.password,
33
+ phone: req.body.phone,
34
+ status: req.body.status,
35
+ };
36
+
37
+ try {
38
+ await User.create({
39
+ name: input.name,
40
+ email: input.email,
41
+ password: input.password,
42
+ phone: input.phone,
43
+ status: input.status === 'true',
44
+ });
45
+
46
+ req.flash('success', 'User created successfully!');
47
+ res.redirect('/users');
48
+ } catch (e) {
49
+ if (e instanceof ValidationError) {
50
+ return res.status(422).json(e.errors);
51
+ }
52
+ throw e;
53
+ }
54
+ }
55
+
56
+ // PUT /users/:id
57
+ async update(req, res) {
58
+ try {
59
+ const user = await User.find(req.params.id);
60
+ if (!user) return res.status(404).json({ error: 'User not found.' });
61
+
62
+ await user.fill(req.body);
63
+ await user.save();
64
+
65
+ return res.json(user);
66
+ } catch (err) {
67
+ return res.status(400).json({ error: 'Failed to update user.' });
68
+ }
69
+ }
70
+
71
+ // DELETE /users/:id
72
+ async destroy(req, res) {
73
+ try {
74
+ const user = await User.find(req.params.id);
75
+ if (!user) return res.status(404).json({ error: 'User not found.' });
76
+
77
+ await user.delete();
78
+ return res.status(204).send();
79
+ } catch (err) {
80
+ return res.status(500).json({ error: 'Failed to delete user.' });
81
+ }
82
+ }
83
+
84
+ // POST /users/:id/restore
85
+ async restore(req, res) {
86
+ try {
87
+ const user = await User.withTrashed().where('id', req.params.id).first();
88
+ if (!user) return res.status(404).json({ error: 'User not found.' });
89
+
90
+ await user.restore();
91
+ return res.json(user);
92
+ } catch (err) {
93
+ return res.status(500).json({ error: 'Failed to restore user.' });
94
+ }
95
+ }
96
+ }
97
+
98
+ module.exports = new UserController();