Skip to content

Commit

Permalink
Merge pull request #63 from ASparton/feat/22-get-all-cryptos
Browse files Browse the repository at this point in the history
feat(packages): add cctx package to query cryptocurrencies info
  • Loading branch information
alexis-moins authored Dec 4, 2023
2 parents 5e3f19c + f02684e commit 3020ca5
Show file tree
Hide file tree
Showing 13 changed files with 167 additions and 29 deletions.
4 changes: 4 additions & 0 deletions back/.dockerignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
node_modules
Dockerfile
Session.vim
insomnia.json
README.md
.tools-version
2 changes: 1 addition & 1 deletion back/insomnia.json

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions back/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions back/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"dependencies": {
"@lucia-auth/adapter-prisma": "^3.0.2",
"@prisma/client": "5.6.0",
"ccxt": "^4.1.67",
"cors": "^2.8.5",
"cron": "^3.1.6",
"express": "4.18.2",
Expand Down
3 changes: 1 addition & 2 deletions back/prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ const prismaClient = new PrismaClient();

async function main() {
console.log(`Start seeding ...`);
// TODO: Real user population working with lucia
await populateUser(prismaClient);
await populateUser();
await populateFeeds(prismaClient);
await populateArticles(prismaClient);
await populateCryptos(prismaClient);
Expand Down
27 changes: 21 additions & 6 deletions back/prisma/seedingOperatons.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Article, Crypto, Feed, Prisma, PrismaClient, User } from '@prisma/client';
import { DefaultArgs } from '@prisma/client/runtime/library';
import { auth } from '~lucia';

/****************/
/* EXAMPLE DATA */
Expand Down Expand Up @@ -139,15 +140,29 @@ export const exampleCryptos: Crypto[] = [
}
]

export async function populateUser(
prismaClient: PrismaClient<Prisma.PrismaClientOptions, never, DefaultArgs>
) {
export async function populateUser() {
console.log('Start populating User...');
for (const exampleUser of exampleUsers) {
const user = await prismaClient.user.create({
data: exampleUser,
const user = await auth.createUser({
key: {
providerId: 'email',
providerUserId: exampleUser.email,
password: "mySecuredPassword",
},
attributes: {
email: exampleUser.email,
username: exampleUser.username,
currency: exampleUser.currency,
is_admin: exampleUser.is_admin
},
});
console.log(`Created user with id: ${user.id} and email: ${user.email}`);

await auth.createSession({
userId: user.userId,
attributes: {},
});

console.log(`Created user with id: ${user.userId} and email: ${user.email}`);
}
console.log('User population finished.');
}
Expand Down
13 changes: 13 additions & 0 deletions back/src/composables/useCrypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { binance } from 'ccxt';

const _exchange = new binance();

async function getAllCrypto(cryptos: string[]) {
return await _exchange.fetchTickers(cryptos);
}

const useCrypto = () => ({
getAllCrypto,
});

export default useCrypto;
81 changes: 63 additions & 18 deletions back/src/controllers/cryptos.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,86 @@
import HttpStatusCode from '#types/HttpStatusCode';

import UrlParamIdDTO from '#types/dto/UrlParamIdDTO';
import UpdateFeedDto from '#types/dto/feeds/UpdateFeedDTO';
import UrlQueryIdListDTO from '#types/dto/UrlQueryIdListDTO';

import express from 'express';
import useCrypto from '@composables/useCrypto';

import CreateCryptoDto from '#types/dto/cryptos/CreateCryptoDTO';
import UpdateCryptoDto from '#types/dto/cryptos/UpdateCryptoDTO';

import {
createCrypto,
deleteCryptoById,
updateCryptoById,
findManyCryptosById,
findAllVisibleCryptos,
} from '@database/cryptos';
import { findAllFeeds, updateFeedById } from '@database/feeds';

import { adminRoleRequired, authenticationRequired } from '~middlewares';

const { getAllCrypto } = useCrypto();
const controller = express.Router();

controller.get('/', async (_, res) => {
return res.status(HttpStatusCode.OK_200).send(await findAllFeeds());
});
controller.get('/', async (req, res) => {
const query = UrlQueryIdListDTO.parse(req.query);
const currency = req.lucia ? req.lucia.user.currency : 'EUR';

controller.get('/:id', async (req, res) => {
const urlParams = UrlParamIdDTO.parse(req.params);
const body = UpdateFeedDto.parse(req.body);
return res
.status(HttpStatusCode.OK_200)
.send(await updateFeedById(urlParams.id, body.minArticlesCount));
});
const cryptos = query.ids
? await findManyCryptosById(query.ids)
: await findAllVisibleCryptos();

const tickers: string[] = [];

const cryptoWithTicker = cryptos.map((crypto) => {
const ticker = `${crypto.api_id}/${currency}`;

tickers.push(ticker);
return { ticker, ...crypto };
});

controller.get('/:id/history/:period', async (req, res) => {
const urlParams = UrlParamIdDTO.parse(req.params);
const body = UpdateFeedDto.parse(req.body);
return res
.status(HttpStatusCode.OK_200)
.send(await updateFeedById(urlParams.id, body.minArticlesCount));
if (tickers.length === 0) {
return res.status(HttpStatusCode.OK_200).json([]);
}

const apiResponse = await getAllCrypto(tickers);

const response = cryptoWithTicker.map((crypto) => {
const data = apiResponse[crypto.ticker];

if (!data) {
return;
}

return {
name: crypto.name,
current_price: data.last,
opening_price: data.open,
lowest_price: data.low,
highest_price: data.high,
image: crypto.logo_url,
};
});

return res.status(HttpStatusCode.OK_200).send(response);
});

// controller.get('/:id', async (req, res) => {
// const urlParams = UrlParamIdDTO.parse(req.params);
// const body = UpdateFeedDto.parse(req.body);
// return res
// .status(HttpStatusCode.OK_200)
// .send(await updateFeedById(urlParams.id, body.minArticlesCount));
// });

// controller.get('/:id/history/:period', async (req, res) => {
// const urlParams = UrlParamIdDTO.parse(req.params);
// const body = UpdateFeedDto.parse(req.body);
// return res
// .status(HttpStatusCode.OK_200)
// .send(await updateFeedById(urlParams.id, body.minArticlesCount));
// });

controller.post(
'/',
authenticationRequired,
Expand Down
6 changes: 6 additions & 0 deletions back/src/database/cryptos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,9 @@ export async function addCryptoToUser(userId: string, cryptos: number[]) {
})),
});
}

export async function findAllVisibleCryptos() {
return await database.crypto.findMany({
where: { visible: true },
});
}
4 changes: 2 additions & 2 deletions back/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import articlesHarvestJob from './jobs/articlesHarvest.job';
import app from './app';
import articlesHarvestJob from '@jobs/articlesHarvest.job';
import app from '~app';

const PORT = 3000;

Expand Down
17 changes: 17 additions & 0 deletions back/src/types/dto/UrlQueryIdListDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { z } from 'zod';

/**
* Retun a list of number given a list of ids as a string, separated by ';'
*/
const convertStringToIdList = (ids: string) => {
return ids
.split(';')
.map((id) => parseInt(id))
.filter((id) => !Number.isNaN(id));
};

const UrlParamIdDTO = z.object({
ids: z.string().transform(convertStringToIdList).optional(),
});

export default UrlParamIdDTO;
2 changes: 2 additions & 0 deletions back/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"paths": {
"@controllers/*": ["src/controllers/*"],
"@composables/*": ["src/composables/*"],
"@jobs/*": ["src/jobs/*"],
"~lucia": ["src/lucia.ts"],
"~app": ["src/app.ts"],
"~middlewares": ["src/middlewares.ts"],
"~apiErrors": ["src/apiErrors.ts"],
"#types/*": ["src/types/*"],
Expand Down
3 changes: 3 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ update SERVICE:
migrate:
@docker compose exec {{BACKEND_SERVICE}} {{MIGRATE_COMMAND}}

seed:
@docker compose exec {{BACKEND_SERVICE}} npx prisma db seed

db:
@docker compose exec -it {{DATABASE_SERVICE}} {{DATABASE_ACCESS_COMMAND}}

Expand Down

0 comments on commit 3020ca5

Please sign in to comment.