Skip to content

Commit

Permalink
client web socket implemantation 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
Oğuzhan Aydın committed Apr 28, 2021
1 parent 0bccf51 commit a84f9c9
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 20 deletions.
3 changes: 1 addition & 2 deletions client/src/configs/web-socket.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr'
import { getServiceOrigin } from './origins';

export function createSocketConnection() {
let user = localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))
if (!user || !user.access_token)
return
const connection = new HubConnectionBuilder()
.withUrl(`${getServiceOrigin()}/product-ws/hub/`,{ accessTokenFactory: () => user.access_token })
.withUrl(`http://localhost:5203/hub/`,{ accessTokenFactory: () => user.access_token })
.configureLogging(LogLevel.Information)
.withAutomaticReconnect()
.build()
Expand Down
7 changes: 2 additions & 5 deletions client/src/pages/base/ProfileMenu.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import React from "react";
import { Link } from "react-router-dom";
import { Menu } from "antd";
import {
UserOutlined,
LogoutOutlined,
} from "@ant-design/icons";
import { UnorderedListOutlined, LogoutOutlined } from "@ant-design/icons";

const ProfileMenu = () => {
return (
<Menu>
<Menu.Item key="1">
<Link to="/order">
<UserOutlined />
<UnorderedListOutlined />
Siparişlerim
</Link>
</Menu.Item>
Expand Down
55 changes: 46 additions & 9 deletions client/src/pages/basket/Basket.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,60 @@
import React, { useContext } from "react";
import { List, Typography, Button, message } from "antd";
import React, { useContext, useEffect, useState } from "react";
import { List, Typography, Button, message, Result } from "antd";
import BasketItem from "./BasketItem";
import { BasketContext } from "./BasketContext";
import OrderService from "../order/OrderService";
import { createSocketConnection } from "../../configs/web-socket";

const { Title } = Typography;

const orderService = new OrderService();

const Basket = () => {
const { basket, count } = useContext(BasketContext);
const Basket = ({history}) => {
const connection = createSocketConnection();
const [ready, setReady] = useState(true);
const [error, setError] = useState(null);
const { basket, count, updateBasket, resetCount } = useContext(BasketContext);

useEffect(() => {
connection.start().then(() => console.log("connected"));
connection.on("ProductStockChanged", (result) => {
console.log(result);
setReady(true);
message.success(`Sipariş başarıyla oluşturuldu.`);
updateBasket([]);
resetCount();

connection.on("ProductStockChangedError", (error) => {
setReady(true);
message.error(error);
setError(error);
updateBasket([]);
resetCount();
});
});
}, []);

const createOrder = () => {
orderService
.createOrder({items:[...basket]})
.then(() => message.success(`Sipariş başarıyla oluşturuldu.`))
.createOrder({ items: [...basket] })
.then(() => setReady(false))
.catch((error) => message.error(error.title));
};

return (
return !ready ? (
<Result
status="success"
title="Successfully Purchased Cloud Server ECS!"
subTitle="Order number: 2017182818828182881 Cloud server configuration takes 1-5 minutes, please wait."
extra={[
<Button type="primary" key="console" onClick={() => history.push("/")}>
Go Products
</Button>
]}
/>
) : (
<>
<Title level={2}>Basket {count > 0 && `(${count})`} </Title>


<List
itemLayout="horizontal"
Expand All @@ -31,7 +64,11 @@ const Basket = () => {
<br />
<br />

{count > 0 && <Button type="primary" onClick={createOrder}>Sepeti Onayla</Button>}
{count > 0 && (
<Button type="primary" onClick={createOrder}>
Sepeti Onayla
</Button>
)}
</>
);
};
Expand Down
1 change: 1 addition & 0 deletions client/src/pages/basket/BasketContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ function BasketProvider({ ...rest }) {
value={{
basket: basket || [],
count: basket.length,
resetCount: () => setCount(0),
updateBasket: (value) => {
setBaskets(value);
count++;
Expand Down
2 changes: 1 addition & 1 deletion client/src/pages/order/OrderService.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const DEFAULT_QUERY = "api/v1/orders";
class OrderService {

getOrders = () => axClient.get(`${DEFAULT_QUERY}`);
createOrder = order => axClient.post(`${DEFAULT_QUERY}`, order)
createOrder = order => axClient.post(`api/v1/o/orders`, order)
}

export default OrderService;
4 changes: 2 additions & 2 deletions services/product/Product.Api/Application/Hubs/ProductHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ public class ProductHub : Hub<IProductHub>
{
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, Context.UserIdentifier ?? string.Empty);
await Groups.AddToGroupAsync(Context.ConnectionId, Context?.User?.FindFirst("sub")?.Value);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception ex)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.UserIdentifier ?? string.Empty);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context?.User?.FindFirst("sub")?.Value);
await base.OnDisconnectedAsync(ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public async Task<ProductModel> GetProductAsync(int id)

public async Task<IEnumerable<ProductModel>> GetProductsAsync()
{
var products = await _productRepository.Queryable().Include(x => x.ProductType).ToListAsync();
var products = await _productRepository.Queryable().Include(x => x.ProductType).OrderByDescending(x => x.Id).ToListAsync();

return products.Select(MapToProductModel);
}
Expand Down

0 comments on commit a84f9c9

Please sign in to comment.