Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions fullstack/task/jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import type { Config } from 'jest';

const config: Config = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.ts?$': 'ts-jest',
},
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).ts'],
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'js', 'json'],
moduleDirectories: ['node_modules', 'src'],
collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts', '!src/**/main.ts', '!**/migrations/**'],
verbose: true,
};

export default config;
4 changes: 4 additions & 0 deletions fullstack/task/packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
"version": "1.0.0",
"dependencies": {
"@apollo/client": "3.7.10",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@mui/icons-material": "^7.1.0",
"@mui/material": "^7.1.0",
"graphql": "16.6.0",
"graphql-tag": "2.12.6",
"graphql-ws": "5.12.0",
Expand Down
36 changes: 33 additions & 3 deletions fullstack/task/packages/client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
function App() {
return <p>TODO</p>;
}
import React, { useContext } from 'react';
import { Box, IconButton, Paper, Typography } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
import { ColorModeContext } from './theme';
import ExchangeRates from './components/ExchangeRates/ExchangeRates';

const App: React.FC = () => {
const theme = useTheme();
const colorMode = useContext(ColorModeContext);

return (
<Box >
<Paper
elevation={2}
sx={{
px: 2,
py: 1,
}}
>
<Box sx={{ maxWidth: 1000, mx: 'auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="h6">Exchange Rates</Typography>
<IconButton onClick={colorMode.toggleColorMode} color="inherit">
{theme.palette.mode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />}
</IconButton>
</Box>
</Paper>

<ExchangeRates />
</Box>
);
};

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import React, { useState, useMemo } from 'react';
import RefreshIcon from '@mui/icons-material/Refresh';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import {
Box,
Button,
Chip,
CircularProgress,
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Typography,
} from '@mui/material';
import { useExchangeRates } from '../../hooks/useExchangeRates';

const ExchangeRates: React.FC = () => {
const { exchangeRates, loading, error, age, refetch } = useExchangeRates();
const [search, setSearch] = useState('');

const filtered = useMemo(() => {
if (!search) return exchangeRates;
const lower = search.toLowerCase();
return exchangeRates.filter(r =>
r.currency.toLowerCase().includes(lower) ||
r.code.toLowerCase().includes(lower) ||
String(r.amount).includes(lower) ||
String(r.rate).includes(lower)
);
}, [exchangeRates, search]);

// highlight matching text
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const highlight = (value: string | number) => {
const str = String(value);
if (!search) return str;
const parts = str.split(new RegExp(`(${escapeRegExp(search)})`, 'gi'));
return parts.map((part, i) =>
part.toLowerCase() === search.toLowerCase() ? (
<Box component="span" key={i} sx={{ bgcolor: 'yellow' }}>
{part}
</Box>
) : (
part
)
);
};

return (
<Box sx={{ maxWidth: 1000, mx: 'auto', p: 2 }}>
<Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
<Box display="flex" alignItems="center" gap={1}>
<Chip
icon={<AccessTimeIcon />}
label={`Last fetched: ${age}`}
variant="outlined"
/>
<IconButton
color="primary"
onClick={() => refetch({ bypassCache: true })}
aria-label="refresh rates"
>
<RefreshIcon />
</IconButton>
</Box>
<TextField
size="small"
placeholder="Search..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
</Box>

<TableContainer component={Paper} elevation={3}>
{error ? (
<Box display="flex" justifyContent="center" alignItems="center" minHeight="300px">
<Typography color="error">
Error fetching exchange rates: {error.message}
</Typography>
</Box>
) : loading ? (
<Box display="flex" justifyContent="center" alignItems="center" minHeight="300px">
<CircularProgress />
</Box>
) : (
<Table>
<TableHead>
<TableRow>
<TableCell><strong>Currency</strong></TableCell>
<TableCell><strong>Code</strong></TableCell>
<TableCell align="right"><strong>Amount</strong></TableCell>
<TableCell align="right"><strong>Rate</strong></TableCell>
</TableRow>
</TableHead>
<TableBody>
{filtered.length === 0 ? (
<TableRow>
<TableCell colSpan={4} align="center">
No matching records
</TableCell>
</TableRow>
) : (
filtered.map(r => (
<TableRow key={r.id} hover>
<TableCell>{highlight(r.currency)}</TableCell>
<TableCell>{highlight(r.code)}</TableCell>
<TableCell align="right">{highlight(r.amount)}</TableCell>
<TableCell align="right">{highlight(r.rate.toFixed(4))}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
</TableContainer>
</Box>
);
};

export default ExchangeRates;
59 changes: 59 additions & 0 deletions fullstack/task/packages/client/src/hooks/useExchangeRates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { gql, useQuery } from '@apollo/client';
import { useEffect, useMemo, useState } from 'react';

export interface ExchangeRate {
id: string;
currency: string;
code: string;
amount: number;
rate: number;
createdAtUtc: string;
}

const GET_EXCHANGE_RATES = gql`
query GetExchangeRates($bypassCache: Boolean!) {
exchangeRates(bypassCache: $bypassCache) {
id
currency
code
amount
rate
createdAtUtc
}
}
`;

export function useExchangeRates() {
const { data, loading, error, refetch } = useQuery<
{ exchangeRates: ExchangeRate[] },
{ bypassCache: boolean }
>(GET_EXCHANGE_RATES, {
variables: { bypassCache: false },
pollInterval: 30_000,
fetchPolicy: 'cache-first',
notifyOnNetworkStatusChange: true,
});

const [lastFetched, setLastFetched] = useState<Date | null>(null);

useEffect(() => {
const ts = data?.exchangeRates?.[0]?.createdAtUtc;
if (ts) setLastFetched(new Date(ts));
}, [data]);

const age = useMemo(() => {
if (!lastFetched) return '';
const secs = Math.floor((Date.now() - lastFetched.getTime()) / 1000);
if (secs < 60) return `${secs} second${secs !== 1 ? 's' : ''} ago`;
const mins = Math.floor(secs / 60);
return `${mins} minute${mins !== 1 ? 's' : ''} ago`;
}, [lastFetched]);

return {
exchangeRates: data?.exchangeRates ?? [],
loading,
error,
age,
refetch,
};
}
45 changes: 36 additions & 9 deletions fullstack/task/packages/client/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,44 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import { ThemeProvider, CssBaseline, createTheme } from '@mui/material';
import { getDesignTokens, ColorModeContext } from './theme';
import App from './App';

const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
function Root() {
const [mode, setMode] = React.useState<'light' | 'dark'>('dark');

const colorMode = React.useMemo(() => ({
toggleColorMode: () => {
setMode(prev => (prev === 'light' ? 'dark' : 'light'));
}
}), []);

const theme = React.useMemo(
() => createTheme(getDesignTokens(mode)),
[mode]
);

const client = new ApolloClient({
// Ilkin: better come from env. Also port 4000 was not working locally
uri: 'http://localhost:4001/graphql',
cache: new InMemoryCache(),
});
});

return (
<ApolloProvider client={client}>
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</ColorModeContext.Provider>
</ApolloProvider>
);
}

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Root />
</React.StrictMode>
);
23 changes: 23 additions & 0 deletions fullstack/task/packages/client/src/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import { PaletteMode, ThemeOptions } from '@mui/material';
import { deepOrange, teal } from '@mui/material/colors';

export const ColorModeContext = React.createContext({
toggleColorMode: () => {},
});

export const getDesignTokens = (mode: PaletteMode): ThemeOptions => ({
palette: {
mode,
primary: mode === 'light' ? teal : deepOrange,
},
components: {
MuiButton: {
styleOverrides: {
root: {
textTransform: 'none',
},
},
},
},
});
5 changes: 4 additions & 1 deletion fullstack/task/packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"serve": "node dist/main"
"serve": "node dist/main",
"test": "jest --passWithNoTests",
"test:watch": "jest --watch",
"test:cov": "jest --coverage"
},
"dependencies": {
"@nestjs/apollo": "10.1.3",
Expand Down
20 changes: 16 additions & 4 deletions fullstack/task/packages/server/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,35 @@
# THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)
# ------------------------------------------------------

type Example {
type ExchangeRate {
id: ID!
createdAtUtc: DateTime!
updatedAtUtc: DateTime
deleteDateUtc: DateTime
version: Int!
name: String!
value: String!
currency: String!
code: String!
rate: Float!
amount: Int!
}

"""
A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format.
"""
scalar DateTime

type Example {
id: ID!
createdAtUtc: DateTime!
updatedAtUtc: DateTime
deleteDateUtc: DateTime
version: Int!
name: String!
value: String!
}

type Query {
exchangeRates: String!
exchangeRates(bypassCache: Boolean = false): [ExchangeRate!]!
exampleByName(name: String!): Example
}

Expand Down
Loading