Skip to content

Commit 08a7a98

Browse files
committed
feat(model): add endpoint session
1 parent 509d14c commit 08a7a98

File tree

7 files changed

+266
-0
lines changed

7 files changed

+266
-0
lines changed

src/controllers/Session/controller.ts

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { Request, Response } from 'express'
2+
import routes from 'routes/public'
3+
import asyncHandler from 'helpers/asyncHandler'
4+
import Authorization from 'middlewares/Authorization'
5+
import BuildResponse from 'modules/Response/BuildResponse'
6+
import SessionService from 'controllers/Session/service'
7+
8+
routes.get(
9+
'/session',
10+
asyncHandler(async function getAll(req: Request, res: Response) {
11+
const data = await SessionService.getAll(req)
12+
const buildResponse = BuildResponse.get(data)
13+
14+
return res.status(200).json(buildResponse)
15+
})
16+
)
17+
18+
routes.get(
19+
'/session/:id',
20+
asyncHandler(async function getOne(req: Request, res: Response) {
21+
const { id } = req.getParams()
22+
23+
const data = await SessionService.getOne(id)
24+
const buildResponse = BuildResponse.get({ data })
25+
26+
return res.status(200).json(buildResponse)
27+
})
28+
)
29+
30+
routes.post(
31+
'/session',
32+
Authorization,
33+
asyncHandler(async function createData(req: Request, res: Response) {
34+
const formData = req.getBody()
35+
36+
const data = await SessionService.create(formData)
37+
const buildResponse = BuildResponse.created({ data })
38+
39+
return res.status(201).json(buildResponse)
40+
})
41+
)
42+
43+
routes.put(
44+
'/session/:id',
45+
Authorization,
46+
asyncHandler(async function updateData(req: Request, res: Response) {
47+
const { id } = req.getParams()
48+
const formData = req.getBody()
49+
50+
const data = await SessionService.update(id, formData)
51+
const buildResponse = BuildResponse.updated({ data })
52+
53+
return res.status(200).json(buildResponse)
54+
})
55+
)
56+
57+
routes.delete(
58+
'/session/:id',
59+
Authorization,
60+
asyncHandler(async function forceDelete(req: Request, res: Response) {
61+
const { id } = req.getParams()
62+
63+
await SessionService.delete(id)
64+
const buildResponse = BuildResponse.deleted({})
65+
66+
return res.status(200).json(buildResponse)
67+
})
68+
)

src/controllers/Session/schema.ts

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import * as yup from 'yup'
2+
3+
const create = yup.object().shape({
4+
UserId: yup.string().required('user is required'),
5+
token: yup.string().required('token is required'),
6+
ipAddress: yup.string().nullable(),
7+
device: yup.string().nullable(),
8+
platform: yup.string().nullable(),
9+
})
10+
11+
export default {
12+
create,
13+
}

src/controllers/Session/service.ts

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import { Request } from 'express'
2+
import models from 'models'
3+
import ResponseError from 'modules/Response/ResponseError'
4+
import useValidation from 'helpers/useValidation'
5+
import PluginSqlizeQuery from 'modules/SqlizeQuery/PluginSqlizeQuery'
6+
import schema from 'controllers/Session/schema'
7+
import { SessionAttributes } from 'models/session'
8+
9+
const { Session } = models
10+
11+
class SessionService {
12+
/**
13+
*
14+
* @param req Request
15+
*/
16+
public static async getAll(req: Request) {
17+
const { includeCount, order, ...queryFind } = PluginSqlizeQuery.generate(
18+
req.query,
19+
Session,
20+
[]
21+
)
22+
23+
const data = await Session.findAll({
24+
...queryFind,
25+
order: order.length ? order : [['createdAt', 'desc']],
26+
})
27+
const total = await Session.count({
28+
include: includeCount,
29+
where: queryFind.where,
30+
})
31+
32+
return { message: `${total} data has been received.`, data, total }
33+
}
34+
35+
/**
36+
*
37+
* @param id
38+
*/
39+
public static async getOne(id: string) {
40+
const data = await Session.findByPk(id)
41+
42+
if (!data) {
43+
throw new ResponseError.NotFound(
44+
'session data not found or has been deleted'
45+
)
46+
}
47+
48+
return data
49+
}
50+
51+
/**
52+
*
53+
* @param UserId
54+
* @param token
55+
*/
56+
public static async findByTokenUser(UserId: string, token: string) {
57+
const data = await Session.findOne({ where: { UserId, token } })
58+
59+
if (!data) {
60+
throw new ResponseError.NotFound(
61+
'the login session has ended, please re-login'
62+
)
63+
}
64+
65+
return data
66+
}
67+
68+
/**
69+
*
70+
* @param formData
71+
*/
72+
public static async create(formData: SessionAttributes) {
73+
const value = useValidation(schema.create, formData)
74+
const data = await Session.create(value)
75+
76+
return data
77+
}
78+
79+
/**
80+
*
81+
* @param id
82+
* @param formData
83+
*/
84+
public static async update(id: string, formData: SessionAttributes) {
85+
const data = await this.getOne(id)
86+
87+
const value = useValidation(schema.create, {
88+
...data.toJSON(),
89+
...formData,
90+
})
91+
92+
await data.update(value || {})
93+
94+
return data
95+
}
96+
97+
/**
98+
*
99+
* @param UserId
100+
* @param token
101+
*/
102+
public static async deleteByTokenUser(UserId: string, token: string) {
103+
await Session.destroy({ where: { UserId, token } })
104+
}
105+
106+
/**
107+
*
108+
* @param id - Force Delete
109+
*/
110+
public static async delete(id: string) {
111+
const data = await this.getOne(id)
112+
await data.destroy()
113+
}
114+
}
115+
116+
export default SessionService
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
module.exports = {
2+
up: async (queryInterface, Sequelize) => {
3+
await queryInterface.createTable('Sessions', {
4+
id: {
5+
allowNull: false,
6+
primaryKey: true,
7+
type: Sequelize.UUID,
8+
defaultValue: Sequelize.UUIDV4,
9+
},
10+
UserId: {
11+
type: Sequelize.UUID,
12+
},
13+
token: {
14+
type: Sequelize.TEXT,
15+
},
16+
ipAddress: {
17+
type: Sequelize.STRING,
18+
},
19+
device: {
20+
type: Sequelize.STRING, // Desktop, Mobile, Tablet
21+
},
22+
platform: {
23+
type: Sequelize.STRING, // Android, iOS, Web browser
24+
},
25+
createdAt: {
26+
allowNull: false,
27+
type: Sequelize.DATE,
28+
},
29+
updatedAt: {
30+
allowNull: false,
31+
type: Sequelize.DATE,
32+
},
33+
})
34+
},
35+
down: async (queryInterface, Sequelize) => {
36+
await queryInterface.dropTable('Sessions')
37+
},
38+
}

src/models/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ import Role from './role'
22
import User from './user'
33
import UserRole from './userrole'
44
import RefreshToken from './refreshtoken'
5+
import Session from './session'
56

67
const models = {
78
Role,
89
User,
910
UserRole,
1011
RefreshToken,
12+
Session,
1113
}
1214

1315
export default models

src/models/session.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Model, Optional } from 'sequelize'
2+
import SequelizeAttributes from '../utils/SequelizeAttributes'
3+
4+
import db from './_instance'
5+
6+
export interface SessionAttributes {
7+
id?: string
8+
UserId: string
9+
token: string
10+
ipAddress?: string | null
11+
device?: string | null
12+
platform?: string | null
13+
createdAt?: Date
14+
updatedAt?: Date
15+
deletedAt?: Date | null
16+
}
17+
18+
interface SessionCreationAttributes extends Optional<SessionAttributes, 'id'> {}
19+
20+
export interface SessionInstance
21+
extends Model<SessionAttributes, SessionCreationAttributes>,
22+
SessionAttributes {}
23+
24+
const Session = db.sequelize.define<SessionInstance>('Sessions', {
25+
...SequelizeAttributes.Sessions,
26+
})
27+
28+
export default Session

src/routes/public.ts

+1
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ require('controllers/Auth/controller')
88
require('controllers/Role/controller')
99
require('controllers/User/controller')
1010
require('controllers/RefreshToken/controller')
11+
require('controllers/Session/controller')

0 commit comments

Comments
 (0)