-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: proxy frontend API requests to correct microservice
* Add feeds component * refactor frontend to use proxy instead of the services directly * add api service class to frontend
- Loading branch information
1 parent
583d5e3
commit c9fe33f
Showing
9 changed files
with
221 additions
and
63 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -155,3 +155,6 @@ services: | |
- '/app/node_modules' | ||
ports: | ||
- 3000:3000 | ||
depends_on: | ||
- api | ||
- news |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import React, { useEffect, useState } from 'react'; | ||
import api, { Feeds } from '../services/api'; | ||
|
||
const FeedsComponent = () => { | ||
const [feeds, setFeeds] = useState<Feeds>(); | ||
|
||
useEffect(() => { | ||
api.feeds().then(setFeeds).catch(console.log); | ||
}, []); | ||
|
||
return ( | ||
<> | ||
{feeds | ||
? feeds.map((feed) => { | ||
return ( | ||
<div> | ||
{feed.title} <button>Subscribe</button> | ||
</div> | ||
); | ||
}) | ||
: 'No feeds'} | ||
</> | ||
); | ||
}; | ||
|
||
export default FeedsComponent; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,19 @@ | ||
import React, { useEffect } from 'react'; | ||
import api from '../services/api'; | ||
|
||
interface Props { | ||
token: string; | ||
} | ||
interface Props {} | ||
|
||
const WebSocketComponent = ({ token }: Props) => { | ||
const WebSocketComponent = (_: Props) => { | ||
useEffect(() => { | ||
// Connect to WebSocket server | ||
const socket = new WebSocket('ws://localhost:8000/ws'); | ||
|
||
let interval: string | number | NodeJS.Timer | undefined; | ||
|
||
// WebSocket event listeners | ||
socket.onopen = () => { | ||
console.log('WebSocket connection established.'); | ||
socket.send('/login ' + token); | ||
|
||
interval = setInterval(() => { | ||
socket.send('ping'); | ||
}, 1000); | ||
}; | ||
|
||
socket.onmessage = (event) => { | ||
const connDestruct = api.connectWs((event) => { | ||
console.log('WebSocket message received:', event.data); | ||
// Handle the received message | ||
}; | ||
|
||
socket.onclose = () => { | ||
console.log('WebSocket connection closed.'); | ||
}; | ||
}); | ||
|
||
// Clean up the WebSocket connection when the component unmounts | ||
return () => { | ||
socket.close(); | ||
clearInterval(interval); | ||
}; | ||
return connDestruct; | ||
}, []); | ||
|
||
return <div>WebSocket Component</div>; | ||
return <span aria-description="websocket-placeholder"></span>; | ||
}; | ||
|
||
export default WebSocketComponent; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
type LoginResponse = { | ||
token: string; | ||
}; | ||
|
||
type UserResponse = { | ||
id: string; | ||
name: string; | ||
}; | ||
|
||
export type Feeds = Array<{ | ||
id: string; | ||
url: string; | ||
title: string; | ||
author: string; | ||
publish_date: string; | ||
}>; | ||
|
||
class API { | ||
token: string = ''; | ||
|
||
_doRequest( | ||
input: RequestInfo | URL, | ||
init: RequestInit = {} | ||
): Promise<Response> { | ||
return fetch(`/api${input}`, { | ||
...init, | ||
mode: 'cors', | ||
headers: { | ||
Authorization: `Bearer ${this.token}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
}).then(async (resp) => { | ||
if (resp.status >= 200 && resp.status < 300) { | ||
const json = await resp.json(); | ||
return json; | ||
} | ||
const err = await resp.text(); | ||
throw new Error(err); | ||
}); | ||
} | ||
|
||
_init() { | ||
const authToken = window.localStorage.getItem('authToken'); | ||
|
||
if (authToken) { | ||
this.token = authToken; | ||
} | ||
} | ||
|
||
login(name: string, password: string): Promise<LoginResponse> { | ||
return this._doRequest('/auth/login', { | ||
method: 'POST', | ||
body: JSON.stringify({ name, password }), | ||
}).then((resp: any) => { | ||
window.localStorage.setItem('authToken', resp.token); | ||
return resp; | ||
}) as any; | ||
} | ||
|
||
me(): Promise<UserResponse> { | ||
return this._doRequest('/auth/me') as any; | ||
} | ||
|
||
feeds(): Promise<Feeds> { | ||
return this._doRequest('/feeds') as any; | ||
} | ||
|
||
connectWs(onMessage: (event: MessageEvent<any>) => void) { | ||
// const socket = new WebSocket('ws://localhost:8000/ws'); | ||
const socket = new WebSocket(`ws://${window.location.host}/ws`); | ||
|
||
let interval: string | number | NodeJS.Timer | undefined; | ||
|
||
// WebSocket event listeners | ||
socket.onopen = () => { | ||
console.log('WebSocket connection established.'); | ||
socket.send('/login ' + this.token); | ||
|
||
interval = setInterval(() => { | ||
socket.send('ping'); | ||
}, 1000); | ||
}; | ||
|
||
socket.onmessage = onMessage; | ||
|
||
socket.onclose = () => { | ||
console.log('WebSocket connection closed.'); | ||
}; | ||
|
||
return () => { | ||
socket.close(); | ||
clearInterval(interval); | ||
}; | ||
} | ||
} | ||
|
||
const api = new API(); | ||
|
||
// api.login = api.login.bind(api); | ||
// api.me = api.me.bind(api); | ||
// api.connectWs = api.connectWs.bind(api); | ||
|
||
export default api; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
const { createProxyMiddleware } = require('http-proxy-middleware'); | ||
|
||
module.exports = function (app) { | ||
app | ||
.use( | ||
'/api/news', | ||
createProxyMiddleware({ | ||
target: 'http://news:8001', | ||
changeOrigin: true, | ||
pathRewrite: { | ||
'^/api/': '/', | ||
}, | ||
}) | ||
) | ||
.use( | ||
'/api/feeds', | ||
createProxyMiddleware({ | ||
target: 'http://news:8001', | ||
changeOrigin: true, | ||
pathRewrite: { | ||
'^/api/': '/', | ||
}, | ||
}) | ||
) | ||
.use( | ||
'/api/users', | ||
createProxyMiddleware({ | ||
target: 'http://api:8000', | ||
changeOrigin: true, | ||
pathRewrite: { | ||
'^/api/': '/', | ||
}, | ||
}) | ||
) | ||
.use( | ||
'/api/auth', | ||
createProxyMiddleware({ | ||
target: 'http://api:8000', | ||
changeOrigin: true, | ||
pathRewrite: { | ||
'^/api/': '/', | ||
}, | ||
}) | ||
) | ||
.use( | ||
'/ws', | ||
createProxyMiddleware({ | ||
target: 'ws://api:8000', | ||
changeOrigin: true, | ||
}) | ||
); | ||
}; |