Skip to content

Commit 124a49c

Browse files
authored
Merge pull request #276 from SCVApp/master
db procedure for lockers
2 parents 155fbc7 + f1ed0fd commit 124a49c

File tree

2 files changed

+48
-5
lines changed

2 files changed

+48
-5
lines changed

db_migrations/locker_function.sql

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
CREATE OR REPLACE FUNCTION check_locker_availability()
2+
RETURNS TRIGGER AS $$
3+
DECLARE
4+
old_controller_id INT;
5+
new_locker_id INT;
6+
BEGIN
7+
IF OLD.locker_id IS NULL OR NEW.locker_id != OLD.locker_id THEN
8+
IF EXISTS(SELECT 1 FROM lockers_users WHERE locker_id = NEW.locker_id AND start_time < NOW() AND (end_time IS NULL OR end_time > NOW())) THEN
9+
SELECT controller_id INTO old_controller_id FROM lockers WHERE id = NEW.locker_id;
10+
SELECT id INTO new_locker_id FROM lockers WHERE controller_id = old_controller_id AND id NOT IN (SELECT locker_id FROM lockers_users WHERE start_time < NOW() AND (end_time IS NULL OR end_time > NOW()));
11+
IF new_locker_id IS NULL THEN
12+
RAISE EXCEPTION 'No available lockers';
13+
ELSE
14+
NEW.locker_id := new_locker_id;
15+
END IF;
16+
END IF;
17+
END IF;
18+
19+
RETURN NEW;
20+
END;
21+
$$ LANGUAGE plpgsql;
22+
23+
CREATE TRIGGER validate_locker
24+
BEFORE INSERT OR UPDATE ON lockers_users
25+
FOR EACH ROW
26+
EXECUTE FUNCTION check_locker_availability();

src/lockers/lockers.service.ts

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,14 +135,31 @@ export class LockersService {
135135
if (!firstAvailableLocker) {
136136
throw new NotFoundException('No lockers available');
137137
}
138-
const success = await this.openLocker(firstAvailableLocker);
138+
139+
// This is the check from db, becouse we have a trigger on lockers_users table and if we insert already used locker, it will change the locker with the first available one
140+
const result = await this.lockersUsersRepository
141+
.insert({
142+
user,
143+
locker: firstAvailableLocker,
144+
})
145+
.catch(() => {
146+
throw new InternalServerErrorException('No lockers available');
147+
});
148+
if (!result) {
149+
throw new NotFoundException('No lockers available');
150+
}
151+
const assignedLocker = await this.getUsersActiveLocker(user);
152+
if (!assignedLocker) {
153+
throw new NotFoundException('No lockers available');
154+
}
155+
const success = await this.openLocker(assignedLocker);
139156
if (!success) {
157+
await this.lockersUsersRepository.delete({
158+
user,
159+
locker: assignedLocker,
160+
});
140161
throw new InternalServerErrorException('Failed to open locker');
141162
}
142-
await this.lockersUsersRepository.save({
143-
user,
144-
locker: firstAvailableLocker,
145-
});
146163
return { success: true };
147164
}
148165

0 commit comments

Comments
 (0)