Skip to content

Commit

Permalink
refactor: serve sound data files from backend
Browse files Browse the repository at this point in the history
- Updates build method to generate to the backend folder
- Adjust express static files config to use cors as well
- Update .gitignore to match new served data path
- Updates backend to use its own url and frontend to make a normal fetch to the backend
  • Loading branch information
Bentroen committed Jul 7, 2024
1 parent 1e8886c commit d0d1d9a
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 33 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Data files
web/public/data/
shared/data/
server/public/data/

# Logs
logs
Expand Down
33 changes: 13 additions & 20 deletions build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,24 @@ function writeJSONFile(
writeFileSync(path, jsonString);
}

const frontEndDataDir = resolve(__dirname, 'web', 'public', 'data');
const sharedDataDir = resolve(__dirname, 'shared', 'data');
const dataDir = resolve(__dirname, 'server', 'public', 'data');

const soundListPath = 'soundList.json';
const filteredSoundListPath = 'filteredSoundList.json';

// Try to create the directories if they don't exist
[frontEndDataDir, sharedDataDir].forEach((dir) => {
try {
mkdirSync(dir, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
// Try to create the output directory if it doesn't exist
try {
mkdirSync(dataDir, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
});
}

// If the files already exist, exit early
const files = [soundListPath, filteredSoundListPath]
.map((fileName) =>
[frontEndDataDir, sharedDataDir].map((dir) => resolve(dir, fileName)),
)
.flat();
const files = [soundListPath, filteredSoundListPath].map((fileName) =>
resolve(dataDir, fileName),
);

if (files.every((file) => existsSync(file))) {
console.log('Sound data files already exist; skipping generation.');
Expand All @@ -53,8 +48,6 @@ getLatestVersionSoundList().then((soundList) => {
SEARCH_INCLUDE_PATTERNS.some((pattern) => new RegExp(pattern).test(sound)),
);

[frontEndDataDir, sharedDataDir].forEach((dir) => {
writeJSONFile(dir, soundListPath, soundList);
writeJSONFile(dir, filteredSoundListPath, filteredSoundList);
});
writeJSONFile(dataDir, soundListPath, soundList);
writeJSONFile(dataDir, filteredSoundListPath, filteredSoundList);
});
3 changes: 2 additions & 1 deletion server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const logger: Logger = new Logger('main.ts');
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api/v1');
app.use('/public', express.static('public'));

const parseTokenPipe = app.get<ParseTokenPipe>(ParseTokenPipe);

Expand Down Expand Up @@ -41,6 +40,8 @@ async function bootstrap() {
credentials: true,
});

app.use('/api/v1', express.static('public'));

const port = process.env.PORT || '4000';

logger.log('Note Block World API Backend 🎶🌎🌍🌏 ');
Expand Down
14 changes: 6 additions & 8 deletions server/src/song/song-upload/song-upload.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { drawToImage } from '@shared/features/thumbnail';
import { SongStats } from '@shared/validation/song/dto/SongStats';
import { ThumbnailData } from '@shared/validation/song/dto/ThumbnailData.dto';
import { UploadSongDto } from '@shared/validation/song/dto/UploadSongDto.dto';
import axios from 'axios';
import { Model, Types } from 'mongoose';

import { FileService } from '@server/file/file.service';
Expand Down Expand Up @@ -47,12 +46,11 @@ export class SongUploadService {
// Object that maps sound paths to their respective hashes

if (!this.soundsMapping) {
// TODO: should fetch from the backend's static files, or from S3 bucket
const response = await axios.get<Record<string, string>>(
'http://localhost:3000/data/soundList.json',
const response = await fetch(
process.env.SERVER_URL + '/api/v1/data/soundList.json',
);

this.soundsMapping = await response.data;
this.soundsMapping = (await response.json()) as Record<string, string>;
}

return this.soundsMapping;
Expand All @@ -63,11 +61,11 @@ export class SongUploadService {
// a manually-crafted subset of sounds from Minecraft

if (!this.soundsSubset) {
const response = await axios.get<string[]>(
'http://localhost:3000/data/filteredSoundList.json',
const response = await fetch(
process.env.SERVER_URL + '/api/v1/data/filteredSoundList.json',
);

const soundList = await response.data;
const soundList = (await response.json()) as string[];
this.soundsSubset = new Set(soundList);
}

Expand Down
10 changes: 8 additions & 2 deletions web/src/modules/song/components/client/InstrumentPicker.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Instrument } from '@shared/features/song/types';
import axios from 'axios';
import { useEffect, useState } from 'react';

import axiosInstance from '@web/src/lib/axios';
import { cn } from '@web/src/lib/tailwind.utils';

import { useSongProvider } from './context/Song.context';
Expand Down Expand Up @@ -87,7 +87,13 @@ const InstrumentTable = ({ type }: { type: 'upload' | 'edit' }) => {
};

async function fetchSoundList() {
const response = await axios<string[]>('/data/filteredSoundList.json');
const response = await axiosInstance.get<string[]>(
'/data/filteredSoundList.json',
{
withCredentials: true,
},
);

const data = response.data;
return data;
}
Expand Down

0 comments on commit d0d1d9a

Please sign in to comment.