Compare commits

..
10 Commits
15 changed files with 440 additions and 34 deletions
+2
View File
@@ -1,11 +1,13 @@
import { Elysia } from 'elysia'
import deviceRouter from '~/modules/device/router'
import authRouter from '~/modules/auth/router'
import topicsRouter from '~/modules/topics/router'
export const router = new Elysia({
name: 'codebase.router',
})
.use(authRouter)
.use(topicsRouter)
.use(deviceRouter)
.get('/', () => ({
message: 'This service is running as expected.',
+33
View File
@@ -32,3 +32,36 @@ export const convertAlphabetString = (input: string): string => {
.filter((s) => s !== '')
.join('')
}
/**
* Converts a two-digit string number (01-26) into its corresponding alphabet character (A-Z).
* @param numStr The two-digit numeric string to convert.
* @returns The alphabet character, or an empty string if invalid.
*/
export const numberStringToAlphabet = (numStr: string): string => {
if (!numStr || numStr.length !== 2) return ''
const position = parseInt(numStr, 10)
if (isNaN(position) || position < 1 || position > 26) return ''
// A is 65 (1 + 64)
return String.fromCharCode(position + 64)
}
/**
* Converts a string of numbers into a string of alphabet characters.
* Example: "010203" -> "ABC"
* @param input The string of numbers (must be even length).
* @returns The converted alphabet string.
*/
export const convertNumberStringToAlphabet = (input: string): string => {
if (!input || input.length % 2 !== 0) return ''
const result: string[] = []
for (let i = 0; i < input.length; i += 2) {
const part = input.substring(i, i + 2)
result.push(numberStringToAlphabet(part))
}
return result.join('')
}
+14 -4
View File
@@ -5,22 +5,32 @@ export const passwordVerify = (password: string, hash: string) => Bun.password.v
export const dataMapping = [
{
deviceName: 'AC',
deviceType: 'S',
command: 'AC=',
},
{
deviceName: 'AC',
deviceType: 'A',
command: 'Temp=',
},
{
deviceName: 'L',
deviceType: 'S',
command: 'Light=',
},
{
deviceName: 'DL',
deviceType: 'S',
command: 'Doorlock=',
},
{
deviceName: 'BL',
command: 'Blind=',
},
{
deviceName: 'BL',
deviceType: 'S',
command: 'Blind=',
},
]
export const getDeviceCommand = (deviceName: string, deviceType: string): string => {
const device = dataMapping.find((item) => item.deviceName === deviceName && item.deviceType === deviceType)
return device?.command || ''
}
+11 -9
View File
@@ -1,16 +1,16 @@
import { HTTPHeaders, StatusMap } from 'elysia'
import { Elysia } from 'elysia'
import { basicAuth as credential } from '~/config'
import { UnauthenticatedError } from '~/helpers/errors'
import { logger } from '~/plugins'
export const basicAuthMiddleware = (
headers: Record<string, string | undefined>,
set: {
headers: HTTPHeaders
status?: number | keyof StatusMap
},
) => {
export const basicAuthMacro = new Elysia()
.macro({
verifyBasicAuth: (enabled: boolean) => ({
beforeHandle({ set, headers }) {
if (!enabled) return
const expectedAuth = Buffer.from(`${credential.username}:${credential.password}`).toString('base64')
if (headers.authorization !== `Basic ${expectedAuth}`) {
logger.debug({
'headers.authorization': headers.authorization,
@@ -19,4 +19,6 @@ export const basicAuthMiddleware = (
set.headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
throw new UnauthenticatedError('Unauthenticated.')
}
}
},
}),
})
+1 -1
View File
@@ -1,2 +1,2 @@
export { basicAuthMiddleware } from './basicAuth'
export { basicAuthMacro } from './basicAuth'
export { bearerAuthMiddleware } from './bearerAuth'
+4 -4
View File
@@ -1,7 +1,7 @@
import { Elysia, t } from 'elysia'
import { createMerchantBody, createMerchantResponseSchema } from './schema'
import CreateMerchantService from './commands/service'
import { basicAuthMiddleware } from '~/middlewares/basicAuth'
import { basicAuthMacro } from '~/middlewares/basicAuth'
import { DataAlreadyExistsError } from '~/helpers/errors'
import { apiKeyAuthMacro } from '~/middlewares/apiKeyAuth'
@@ -10,9 +10,8 @@ export const router = new Elysia({
detail: { tags: ['Auth'] },
prefix: '/auth',
})
.post('/get-key', async ({ body, headers, set }) => {
basicAuthMiddleware(headers, set)
.use(basicAuthMacro)
.post('/get-key', async ({ body, set }) => {
try {
const result = await CreateMerchantService.createMerchant(body)
return {
@@ -39,6 +38,7 @@ export const router = new Elysia({
response: createMerchantResponseSchema,
detail: {
security: [{ basicAuth: [] }],
verifyBasicAuth: true,
},
})
.use(apiKeyAuthMacro)
+3 -3
View File
@@ -1,4 +1,4 @@
import { dataMapping } from '~/helpers/utils'
import { getDeviceCommand } from '~/helpers/utils'
import { DeviceCommandBody } from '../schema'
import { sendCommandToThirdParty } from './command'
import { alphabetToNumberString } from '~/helpers/alphabet_conversion'
@@ -11,8 +11,8 @@ export default abstract class CommandService {
}> {
const unitNumber = alphabetToNumberString(body.unitNumber)
const topicData = `${body.merchantName}/${body.floorName}_${unitNumber}-${body.deviceName}-${body.roomName}-${body.deviceType}-${body.commandType}-${body.towerNumber}`
const cmd = dataMapping.find((device) => device.deviceName == body.deviceName)
const request = await sendCommandToThirdParty(topicData, `${cmd?.command}${body.payload.action}`)
const cmd = getDeviceCommand(body.deviceName, body.deviceType)
const request = await sendCommandToThirdParty(topicData, `${cmd}${body.payload.action}`)
if (request.status !== 200 || request.data.status == 400) {
return {
status: 'error' as const,
+5 -3
View File
@@ -1,4 +1,4 @@
import { alphabetToNumberString } from '~/helpers/alphabet_conversion'
import { alphabetToNumberString, convertNumberStringToAlphabet } from '~/helpers/alphabet_conversion'
import { sendQueryToThirdParty } from '../commands/command'
import { DeviceQueryParams } from '../schema'
@@ -39,13 +39,15 @@ export default abstract class QueryService {
message: 'command accepted',
data: {
floorName: request.data.data.floor,
unitNumber: request.data.data.unit,
unitNumber: convertNumberStringToAlphabet(request.data.data.unit),
deviceName: request.data.data.device,
roomName: request.data.data.room,
deviceType: request.data.data.devType,
code: request.data.data.code,
towerNumber: request.data.data.tower,
payload: request.data.data.payload?.split('=')[1],
payload: request.data.data.payload?.includes('=')
? request.data.data.payload?.split('=')[1]
: request.data.data.payload || '',
},
}
}
+84
View File
@@ -0,0 +1,84 @@
import { httpConfig } from '~/config'
import logger from '~/plugins/logger'
import { PatchTopic, PostDeletetopic } from '../schema'
export async function postTopic(payload: PostDeletetopic) {
try {
const request = await fetch(`${httpConfig.baseUrl}/addTopic`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
if (request.status != 200) {
return {
status: request.status,
message: request.statusText,
data: null,
}
}
return {
status: request.status,
message: request.statusText,
data: await request.json(),
}
} catch (e) {
logger.error(e, 'ERROR')
throw e
}
}
export async function delTopic(payload: PostDeletetopic) {
try {
const request = await fetch(`${httpConfig.baseUrl}/deleteTopic`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
if (request.status != 200) {
return {
status: request.status,
message: request.statusText,
data: null,
}
}
return {
status: request.status,
message: request.statusText,
data: await request.json(),
}
} catch (err) {
logger.error(err)
throw err
}
}
export async function patchTopic(payload: PatchTopic) {
try {
const request = await fetch(`${httpConfig.baseUrl}/editTopic`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
if (request.status != 200) {
return {
status: request.status,
message: request.statusText,
data: null,
}
}
return {
status: request.status,
message: request.statusText,
data: await request.json(),
}
} catch (err) {
logger.error(err)
throw err
}
}
+51
View File
@@ -0,0 +1,51 @@
import { PatchTopic, PostDeleteTopicResponseSchema, PostDeletetopic } from '../schema'
import { delTopic, patchTopic, postTopic } from './command'
export default abstract class CommandService {
static async postTopic(body: PostDeletetopic): Promise<PostDeleteTopicResponseSchema> {
const postRequest = await postTopic(body)
if (postRequest.status != 200) {
return {
status: postRequest.status,
message: postRequest.message,
data: null,
}
}
return {
status: 200,
message: 'Create topic success',
data: null,
}
}
static async delTopic(body: PostDeletetopic): Promise<PostDeleteTopicResponseSchema> {
const postRequest = await delTopic(body)
if (postRequest.status != 200) {
return {
status: postRequest.status,
message: postRequest.message,
data: null,
}
}
return {
status: 200,
message: 'Delete topic success',
data: null,
}
}
static async patchTopic(body: PatchTopic): Promise<PostDeleteTopicResponseSchema> {
const postRequest = await patchTopic(body)
if (postRequest.status != 200) {
return {
status: postRequest.status,
message: postRequest.message,
data: null,
}
}
return {
status: 200,
message: 'Update topic success',
data: null,
}
}
}
+57
View File
@@ -0,0 +1,57 @@
import { httpConfig } from '~/config'
import logger from '~/plugins/logger'
import { ListTopics } from '../schema'
export async function getCommands(payload: ListTopics) {
try {
const qParams = new URLSearchParams(payload).toString()
const request = await fetch(`${httpConfig.baseUrl}/listCommand?${qParams}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
if (request.status != 200) {
return {
status: request.status,
message: request.statusText,
data: null,
}
}
return {
status: request.status,
message: request.statusText,
data: await request.json(),
}
} catch (err) {
logger.error(err)
throw err
}
}
export async function getStateReply(payload: ListTopics) {
try {
const qParams = new URLSearchParams(payload).toString()
const request = await fetch(`${httpConfig.baseUrl}/listState-reply?${qParams}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
if (request.status != 200) {
return {
status: request.status,
message: request.statusText,
data: null,
}
}
return {
status: request.status,
message: request.statusText,
data: await request.json(),
}
} catch (err) {
logger.error(err)
throw err
}
}
+36
View File
@@ -0,0 +1,36 @@
import { ListTopics } from '../schema'
import { getCommands, getStateReply } from './query'
export default abstract class QueryService {
static async getCommands(payload: ListTopics) {
const result = await getCommands(payload)
if (result.status != 200) {
return {
status: result.status,
message: result.message,
data: null,
}
}
return {
status: 200,
message: 'Get commands success',
data: result.data.data,
}
}
static async getStateReply(payload: ListTopics) {
const result = await getStateReply(payload)
if (result.status != 200) {
return {
status: result.status,
message: result.message,
data: null,
}
}
return {
status: 200,
message: 'Get state-reply success',
data: result.data.data,
}
}
}
+74
View File
@@ -0,0 +1,74 @@
import { Elysia } from 'elysia'
import CommandService from './commands/service'
import { listTopicResponseSchema, listTopics, patchTopic, postDeleteTopic, postDeleteTopicResponseSchema } from './schema'
import QueryService from './queries/service'
import { basicAuthMacro } from '../../middlewares/basicAuth'
export const router = new Elysia({
name: 'modules.topics',
detail: { tags: ['Topics'] },
prefix: '/topics/v1',
})
.use(basicAuthMacro)
.get('/state-reply', async ({ query, set }) => {
const result = await QueryService.getStateReply(query)
if (result.status != 200) {
set.status = result.status
return result
}
return result
}, {
query: listTopics,
response: listTopicResponseSchema,
verifyBasicAuth: true,
})
.get('/commands', async ({ query, set }) => {
const result = await QueryService.getCommands(query)
if (result.status != 200) {
set.status = result.status
return result
}
return result
}, {
query: listTopics,
response: listTopicResponseSchema,
verifyBasicAuth: true,
})
.post('/', async ({ body, set }) => {
const result = await CommandService.postTopic(body)
if (result.status != 200) {
set.status = result.status
return result
}
return result
}, {
body: postDeleteTopic,
response: postDeleteTopicResponseSchema,
verifyBasicAuth: true,
})
.patch('/', async ({ body, set }) => {
const result = await CommandService.patchTopic(body)
if (result.status != 200) {
set.status = result.status
return result
}
return result
}, {
verifyBasicAuth: true,
body: patchTopic,
response: postDeleteTopicResponseSchema,
})
.delete('/', async ({ body, set }) => {
const result = await CommandService.delTopic(body)
if (result.status != 200) {
set.status = result.status
return result
}
return result
}, {
body: postDeleteTopic,
response: postDeleteTopicResponseSchema,
verifyBasicAuth: true,
})
export default router
+54
View File
@@ -0,0 +1,54 @@
import { z } from 'zod'
export const postDeleteTopic = z.object({
topic: z.string(),
type: z.enum(['state-reply', 'command']),
})
export type PostDeletetopic = z.infer<typeof postDeleteTopic>
export const patchTopic = z.object({
oldTopic: z.string(),
newTopic: z.string(),
type: z.enum(['state-reply', 'command']),
})
export type PatchTopic = z.infer<typeof patchTopic>
export const listTopics = z.object({
topic: z.string().optional(),
})
export type ListTopics = z.infer<typeof listTopics>
export const postDeleteTopicResponseSchema = z.object({
status: z.number(),
message: z.string(),
data: z.any().nullable(),
})
export type PostDeleteTopicResponseSchema = z.infer<typeof postDeleteTopicResponseSchema>
export const listTopicResponseSchema = z.object({
status: z.number(),
data: z.array(
z.object({
topic: z.string().nullable(),
}).nullable(),
).nullable(),
})
export type ListTopicResponseSchema = z.infer<typeof listTopicResponseSchema>
export const postDeleteTopicRequestSchema = {
body: postDeleteTopic,
response: {
200: postDeleteTopicResponseSchema,
400: postDeleteTopicResponseSchema,
401: postDeleteTopicResponseSchema,
},
}
export const listTopicRequestSchema = {
query: listTopics,
response: {
200: listTopicResponseSchema,
400: listTopicResponseSchema,
401: listTopicResponseSchema,
},
}
+2 -1
View File
@@ -19,11 +19,12 @@ export const swaggerPlugin = openapi({
'tags': [
{ name: 'Auth', description: 'Auth API' },
{ name: 'Device', description: 'Device API' },
{ name: 'Topics', description: 'Management Topic' },
],
// --- Grouping di atas tag ---
'x-tagGroups': [
{ name: 'Auth', tags: ['Auth'] },
{ name: 'Device', tags: ['Device'] },
{ name: 'Device', tags: ['Device', 'Topics'] },
],
'components': {
securitySchemes: {