当用户进行事件时 登录的用户ID应该保存到数据库中
有关系
@ManyToOne(_ => User, user => user.events, {
eager: true,
cascade: true
})
users: User;
在事件实体中(许多事件可能是一个用户)
我的用户实体关系
@OneToMany(_ => Event, event => event.users, {
eager: false
})
events: Event[];
在数据库中,显示所有字段(主ID,名称,描述,图像,startDate,endDate)以及一个users_id。 据说应该使用已登录的用户ID
事件控制器具有
@Post decorator
@Authorized()
@Post("/events")
@HttpCode(201)
createEvent(@Body() event: Event) {
return event.save();
}
和前端 我的动作发送数据库中字段的所有值 (当我创建一个事件时,所有值都已存储)
export const addEvent = event => (dispatch, getState) => {
const state = getState();
const jwt = state.currentUser.jwt;
if (isExpired(jwt)) return dispatch(logout());
request
.post(`${baseUrl}/events`)
.set("Authorization", `Bearer ${jwt}`)
.send({
name: event.name,
description: event.description,
startDate: event.startDate,
endDate: event.endDate,
image: event.image
})
.then(response =>
dispatch({
type: ADD_EVENT,
payload: response.body
})
);
};
我还为currentUser发送了一个jwt
我有一个例子来自 我们学习如何使用网络套接字的样板
@Authorized()
@Post("/games/:id([0-9]+)/players")
@HttpCode(201)
async joinGame(@CurrentUser() user: User, @Param("id") gameId: number) {
const game = await Game.findOneById(gameId);
if (!game) throw new BadRequestError(`Game does not exist`);
if (game.status !== "pending")
throw new BadRequestError(`Game is already started`);
game.status = "started";
await game.save();
const player = await Player.create({
game,
user,
symbol: "o"
}).save();
io.emit("action", {
type: "UPDATE_GAME",
payload: await Game.findOneById(game.id)
});
return player;
}
何时创建新游戏 它还存储创建游戏的用户
所以我认为这与 @CurrentUser()用户:用户
但是我不知道 如何在此项目中实现@Post eventsController
如果有人可以告诉我 并简要说明其工作方式和原因 我将继续谷歌搜索。
答案 0 :(得分:0)
我更改了@Post
到
@Authorized()
@Post('/events')
@HttpCode(201)
async createEvent(
@CurrentUser() user: User,
@Body() event: Event,
) {
if (user instanceof User) event.users = user
const entity = event.save()
return { entity }
}
}
显然,它需要一个 currentUserChecker函数
currentUserChecker: async (action: Action) => {
const header: string = action.request.headers.authorization
if (header && header.startsWith('Bearer ')) {
const [, token] = header.split(' ')
if (token) {
const { id } = verify(token)
return User.findOne(id)
}
}
return undefined
}
我不得不更改jwt.ts
来自
import * as jwt from 'jsonwebtoken'
const secret = process.env.JWT_SECRET || '9u8nnjksfdt98*(&*%T$#hsfjk'
const ttl = 3600 * 4 // our JWT tokens are valid for 4 hours
interface JwtPayload {
id: number
}
export const sign = (data: JwtPayload) =>
jwt.sign({ data }, secret, { expiresIn: ttl })
export const verify = (token: string): { data: JwtPayload } =>
jwt.verify(token, secret) as { data: JwtPayload }
到
import * as jwt from 'jsonwebtoken'
const secret = process.env.JWT_SECRET || '9u8nnjksfdt98*(&*%T$#hsfjk'
const ttl = 3600 * 4 // our JWT tokens are valid for 4 hours
interface JwtPayload {
id: number
}
export const sign = (data: JwtPayload) =>
jwt.sign({ data }, secret, { expiresIn: ttl })
export const verify = (token: string): JwtPayload =>
jwt.verify(token, secret) as JwtPayload