Skip to content

Commit

Permalink
feat(): enable api prefix in path if required
Browse files Browse the repository at this point in the history
  • Loading branch information
piyook committed May 21, 2024
1 parent bc1f591 commit c1e4265
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 10 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
SERVER_PORT=8000
SERVER_PORT=8000
USE_API_URL_PREFIX=api
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ services:
NODE_ENV: development
HUSKY: 0
SERVER_PORT: 8000
USE_API_URL_PREFIX: api
ports:
- 8000:8000
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"dev": "tsx watch ./src/server.ts",
"start": "docker compose up -d --force-recreate",
"stop": "docker compose down --volumes",
"rebuild": "docker compose down --volumes && docker compose up -d --force-recreate --build",
"restart": "npm stop && npm start",
"nuke": "bash nuke.sh",
"prepare": "husky || true",
Expand Down
8 changes: 6 additions & 2 deletions src/api/posts/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import { db } from '../../models/db.js';

// Example of msw data auto REST handler generation
function handler(pathName: string) {
return [...db.post.toHandlers('rest')];
// Need to add a prefix here for automatic REST handler generation to a specific path
const prefix = process.env?.USE_API_URL_PREFIX
? '/' + process.env.USE_API_URL_PREFIX
: '';
return [...db.post.toHandlers('rest', prefix)];
}

export default handler;

// To test localhost:9090/posts - to see all posts
// To test localhost:9090/api/posts - to see all posts
// to add post send POST request to localhost:9090/posts with body {"userId": 101, "title": "new post title", "body": "new post body"}
// to check its been added visit localhost:9090/posts/101
6 changes: 5 additions & 1 deletion src/api/users/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { db } from '../../models/db.js';

// Example of msw data auto REST handler generation
function handler(pathName: string) {
return [...db.user.toHandlers('rest')];
// Need to add a prefix here for automatic REST handler generation to a specific path
const prefix = process.env?.USE_API_URL_PREFIX
? '/' + process.env.USE_API_URL_PREFIX
: '';
return [...db.user.toHandlers('rest', prefix)];
}

export default handler;
8 changes: 5 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'dotenv/config';
import { createServer } from '@mswjs/http-middleware';
import { userSeeder, postSeeder } from './seeders/index.js';
import * as seeders from './seeders/index.js';
import getApiPaths from './utilities/file-scan.js';
import serverPage from './utilities/server-page.js';

Expand All @@ -10,7 +10,9 @@ const httpServer = createServer(...apiHandlers, ...serverPage(apiPaths));

httpServer.listen(process.env.SERVER_PORT);

userSeeder();
postSeeder();
// Execute dB seeder functions
for (const seeder of Object.values(seeders)) {
seeder();
}

console.log(`SERVER UP AND RUNNING ON LOCALHOST:${process.env.SERVER_PORT}`);
10 changes: 8 additions & 2 deletions src/utilities/file-scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@ export default async function getApiPaths() {

const files = fs.readdirSync(apiFolder);

const prefix = process.env?.USE_API_URL_PREFIX
? process.env.USE_API_URL_PREFIX + '/'
: '';

for (const file of files) {
const filePath = path.join(apiFolder, file);
const stats = fs.statSync(filePath);

if (stats.isDirectory()) {
// Get the directory name
console.log(`Api Path: /${file}`);
console.log(`Api Path: ${prefix}${file}`);
apiPaths.push(file);

// Import index.ts file (assuming it's in each directory) - this returns a promise
Expand All @@ -46,7 +50,9 @@ export default async function getApiPaths() {
.then((handlers) => {
for (const [index, handler] of handlers.entries()) {
// Add new handlers with the desired apiPath to return array - remember to spread these out as may be more than one
apiHandlers.push(...handler.default(apiPaths[index]));
apiHandlers.push(
...handler.default(`${prefix}${apiPaths[index]}`),
);
}
})
.then(() => {
Expand Down
6 changes: 5 additions & 1 deletion src/utilities/server-page.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import 'dotenv/config';
import { http, HttpResponse } from 'msw';

const prefix = process.env?.USE_API_URL_PREFIX
? process.env.USE_API_URL_PREFIX + '/'
: '';

const homePage = (apiPaths: string[]) => {
const htmlString = `
<html>
<body>
<h3>SERVER RUNNING ON localhost:${process.env.SERVER_PORT} </h3>
<h3>Active Paths:<h4>
<div>
${apiPaths.map((path) => '<h4>/' + path).join('</h4>')}
${apiPaths.map((path) => '<h4>/' + prefix + path).join('</h4>')}
</div>
</body>
</html>
Expand Down

0 comments on commit c1e4265

Please sign in to comment.