Skip to content

Commit

Permalink
#123 Модуль API переведен на TypeScript
Browse files Browse the repository at this point in the history
  • Loading branch information
gbagretsov committed May 16, 2022
1 parent 8ae1ffc commit 991bb43
Show file tree
Hide file tree
Showing 15 changed files with 184 additions and 132 deletions.
29 changes: 0 additions & 29 deletions app/src/api/api.js

This file was deleted.

36 changes: 36 additions & 0 deletions app/src/api/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import express, {Request, Response} from 'express';
import {config} from 'dotenv';

import {router as customReactionsRouter} from './custom-reactions';
import {router as settingsRouter} from './settings';
import {router as wordsRouter} from './words';

const router = express.Router();
config();

function checkToken(req: Request, res: Response, next: () => void): void {
const receivedToken = req.body.token || req.query.token;
const actualToken = process.env.VK_ACCESS_TOKEN;
if (receivedToken === actualToken) {
req.body.demo = false;
next();
} else if (receivedToken && receivedToken.toUpperCase() === 'DEMO') {
req.body.demo = true;
next();
} else {
res.json({ error: 'token' });
}
}

router.use(checkToken);

router.use('/words', wordsRouter);
router.use('/settings', settingsRouter);
router.use('/customReactions', customReactionsRouter);

router.post('/', (req, res) => {
res.json({ success: true, demo: req.body.demo });
});

export { router };

66 changes: 32 additions & 34 deletions app/src/api/custom-reactions.js → app/src/api/custom-reactions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
const express = require('express');
import express from 'express';
import db from '../db';
import {ErrorType} from './model/ErrorType';
import {CustomReactionDto} from './model/custom-reactions-dto/CustomReactionDto';
import {CustomReactionPhraseDto} from './model/custom-reactions-dto/CustomReactionPhraseDto';
import {CustomReactionStickerDto} from './model/custom-reactions-dto/CustomReactionStickerDto';
import {CustomReactionResponseDto} from './model/custom-reactions-dto/CustomReactionResponseDto';
import {CustomReactionPhraseUpdate} from './model/custom-reactions-dto/CustomReactionPhraseUpdate';
import {CustomReactionResponseUpdate} from './model/custom-reactions-dto/CustomReactionResponseUpdate';
import {CustomReactionStickerUpdate} from './model/custom-reactions-dto/CustomReactionStickerUpdate';

const router = express.Router();
const db = require('../db');

router.get('/', async (req, res) => {
try {
Expand All @@ -9,41 +18,29 @@ router.get('/', async (req, res) => {
res.json(customReactions);
} catch(error) {
console.log(error);
res.json({ error: 'internal' });
res.json({ error: ErrorType.INTERNAL });
}
});

router.get('/:id', async (req, res) => {
const id = req.params.id;
try {
let response = await db.query(`SELECT id, name, base_probability AS probability FROM friends_vk_bot.custom_reactions WHERE id = ${id};`);
const customReaction = response.rows[0];
response = await db.query(`SELECT * FROM friends_vk_bot.phrases WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.phrases = response.rows.map(phrase => {
return {
id: phrase.id,
text: phrase.text
};
});
response = await db.query(`SELECT * FROM friends_vk_bot.stickers WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.stickers = response.rows.map(sticker => {
return {
id: sticker.id,
stickerId: sticker.sticker_id,
};
});
response = await db.query(`SELECT * FROM friends_vk_bot.responses WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.responses = response.rows.map(response => {
return {
id: response.id,
type: response.type,
content: response.content
};
});
const customReactionDbResponse = await db.query<CustomReactionDto>(`SELECT id, name, base_probability AS probability FROM friends_vk_bot.custom_reactions WHERE id = ${id};`);
const customReaction = customReactionDbResponse.rows[0];

const phrasesDbResponse = await db.query<CustomReactionPhraseDto>(`SELECT * FROM friends_vk_bot.phrases WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.phrases = phrasesDbResponse.rows;

const stickersDbResponse = await db.query<CustomReactionStickerDto>(`SELECT id, sticker_id AS "stickerId" FROM friends_vk_bot.stickers WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.stickers = stickersDbResponse.rows;

const responsesDbResponse = await db.query<CustomReactionResponseDto>(`SELECT * FROM friends_vk_bot.responses WHERE reaction_id = ${id} ORDER BY id;`);
customReaction.responses = responsesDbResponse.rows;

res.json(customReaction);
} catch(error) {
console.log(error);
res.json({ error: 'internal' });
res.json({ error: ErrorType.INTERNAL });
}
});

Expand All @@ -55,7 +52,7 @@ router.post('/', async (req, res) => {

const { name, probability, phrases, stickers, responses } = req.body.reaction;

const r = await db.query(`INSERT INTO friends_vk_bot.custom_reactions (name, base_probability) VALUES ('${name}', ${probability}) RETURNING id;`);
const r = await db.query<{id: number}>(`INSERT INTO friends_vk_bot.custom_reactions (name, base_probability) VALUES ('${name}', ${probability}) RETURNING id;`);
const reactionId = r.rows[0].id;

let query = 'BEGIN TRANSACTION;\n';
Expand All @@ -67,7 +64,7 @@ router.post('/', async (req, res) => {
res.json({ success: true, id: reactionId });
} catch(error) {
console.log(error);
res.json({ error: 'internal' });
res.json({ error: ErrorType.INTERNAL });
}
});

Expand All @@ -77,7 +74,7 @@ router.post('/:id', async (req, res) => {
return;
}

const reactionId = req.params.id;
const reactionId = parseInt(req.params.id);
const { name, probability, phrases, stickers, responses } = req.body.reaction;

let query = 'BEGIN TRANSACTION;\n';
Expand All @@ -90,7 +87,7 @@ router.post('/:id', async (req, res) => {
res.json({ success: true });
} catch(error) {
console.log(error);
res.json({ error: 'internal' });
res.json({ error: ErrorType.INTERNAL });
}
});

Expand All @@ -112,7 +109,8 @@ router.delete('/:id', async (req, res) => {
}
});

function getQueryForReactionUpdate(reactionId, phrases, stickers, responses) {
function getQueryForReactionUpdate(reactionId: number, phrases: CustomReactionPhraseUpdate[],
stickers: CustomReactionStickerUpdate[], responses: CustomReactionResponseUpdate[]): string {
let query = '';

phrases.forEach(phrase => {
Expand Down Expand Up @@ -153,4 +151,4 @@ function getQueryForReactionUpdate(reactionId, phrases, stickers, responses) {
return query;
}

module.exports.router = router;
export { router };
4 changes: 4 additions & 0 deletions app/src/api/model/ErrorType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum ErrorType {
INTERNAL = 'internal',
DUPLICATE = 'duplicate',
}
12 changes: 12 additions & 0 deletions app/src/api/model/custom-reactions-dto/CustomReactionDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {CustomReactionPhraseDto } from './CustomReactionPhraseDto';
import {CustomReactionStickerDto} from './CustomReactionStickerDto';
import {CustomReactionResponseDto} from './CustomReactionResponseDto';


export type CustomReactionDto = {
id: number,
probability: number,
phrases: CustomReactionPhraseDto[],
stickers: CustomReactionStickerDto[],
responses: CustomReactionResponseDto[],
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type CustomReactionPhraseDto = {
id: number;
text: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import {CustomReactionPhraseDto} from './CustomReactionPhraseDto';

export type CustomReactionPhraseUpdate = CustomReactionPhraseDto & {
deleted: boolean;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type CustomReactionResponseDto = {
id: number;
type: number;
content: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import {CustomReactionResponseDto} from './CustomReactionResponseDto';

export type CustomReactionResponseUpdate = CustomReactionResponseDto & {
deleted: boolean;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type CustomReactionStickerDto = {
id: number;
stickerId: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import {CustomReactionStickerDto} from './CustomReactionStickerDto';

export type CustomReactionStickerUpdate = CustomReactionStickerDto & {
deleted: boolean;
}
5 changes: 5 additions & 0 deletions app/src/api/model/words-dto/WordDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type WordDto = {
id: number;
name: string;
isApproved: boolean;
}
41 changes: 0 additions & 41 deletions app/src/api/settings.js

This file was deleted.

42 changes: 42 additions & 0 deletions app/src/api/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import express from 'express';
import db from '../db';
import {ErrorType} from './model/ErrorType';

const router = express.Router();

router.get('/', async (req, res) => {

try {
const stateRows = await db.query<{key: string; value: string}>('SELECT * FROM friends_vk_bot.state;');
const ads = stateRows.rows.find(row => row.key === 'ads')!.value;
const absentHolidaysPhrases = stateRows.rows.find(row => row.key === 'absent_holidays_phrases')!.value;
res.json({ ads, absentHolidaysPhrases });
} catch(error) {
console.log(error);
res.json({ error: ErrorType.INTERNAL });
}
});

router.post('/', async (req, res) => {
if (req.body.demo) {
res.json({ success: true });
return;
}

const newAds = req.body.ads;
const newAbsentHolidaysPhrases = req.body.absentHolidaysPhrases;
const query = `
UPDATE friends_vk_bot.state SET value = '${ newAds }' WHERE key = 'ads';
UPDATE friends_vk_bot.state SET value = '${ newAbsentHolidaysPhrases }' WHERE key = 'absent_holidays_phrases';
`;

try {
await db.query(query);
res.json({ success: true });
} catch(error) {
console.log(error);
res.json({ error: ErrorType.INTERNAL });
}
});

export { router };
Loading

0 comments on commit 991bb43

Please sign in to comment.