type-graphql#Ctx TypeScript Examples
The following examples show how to use
type-graphql#Ctx.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: plugin-newsletter.resolver.ts From Cromwell with MIT License | 6 votes |
/** Restrict via decorator: */
@Authorized<TAuthRole>("administrator", 'guest')
@Query(() => String)
async pluginNewsletterStats(@Ctx() ctx: TGraphQLContext): Promise<string> {
// Or via checking manually user info: (both methods can work independently)
if (ctx.user?.role !== 'administrator')
throw new UnauthorizedException('Forbidden');
return (await getManager().find(PluginNewsletter) ?? []).length + '';
}
Example #2
Source File: invitation-resolver.ts From convoychat with GNU General Public License v3.0 | 6 votes |
@Authorized()
@Query(() => InvitationDetails)
async getInvitationInfo(
@Arg("token", { nullable: false }) token: string,
@Ctx() context: Context
) {
const invite = await InvitationModel.findOne({
token: token,
})
.populate("roomId")
.populate("invitedBy");
if (!invite) {
throw new ApolloError("Could not get invitation info");
}
const userid = new ObjectID(context.currentUser.id);
const currentUserInvite = userid.equals(invite.userId as ObjectId);
if (!currentUserInvite && !invite.isPublic) {
throw new ApolloError("Could not get invitation info");
}
return {
id: invite.id,
room: invite.roomId,
invitedBy: invite.invitedBy,
isPublic: invite.isPublic,
createdAt: invite.createdAt,
};
}
Example #3
Source File: post.ts From lireddit with MIT License | 6 votes |
@FieldResolver(() => Int, { nullable: true })
async voteStatus(
@Root() post: Post,
@Ctx() { updootLoader, req }: MyContext
) {
if (!req.session.userId) {
return null;
}
const updoot = await updootLoader.load({
postId: post.id,
userId: req.session.userId,
});
return updoot ? updoot.value : null;
}
Example #4
Source File: ChatRoom.resolver.ts From bouncecode-cms with GNU General Public License v3.0 | 6 votes |
@Query(() => [ChatRoomObject])
async chatRooms(
@Arg('where') where: ChatRoomWhereInput,
@Arg('skip', {nullable: true}) skip: number = 0,
@Arg('take', {nullable: true}) take: number = 10,
@Ctx() ctx: Context,
) {
const userId = ctx.user.id;
const queryBuilder = getRepository(UserEntity)
.createQueryBuilder('user')
.leftJoinAndSelect('user.chatRooms', 'chatRooms')
.andWhere('user.id = :userId', {
userId: userId,
});
if (where.category) {
queryBuilder
.leftJoinAndSelect('chatRooms.category', 'category')
.andWhere('category.id = :categoryId', {
categoryId: where.category,
});
}
const result = await queryBuilder
.offset(skip)
.limit(take)
.getMany();
console.log(result);
return result;
}
Example #5
Source File: authentication.ts From backend with MIT License | 6 votes |
@Authorized(Role.UNAUTHENTICATED)
@Mutation(returns => Boolean)
@Deprecated("Use loginPassword instead")
async loginPasswordLegacy(@Ctx() context: GraphQLContext, @Arg("email") email: string, @Arg("password") password: string) {
ensureSession(context);
const logger = logInContext(`GraphQL Authentication`, context);
const screener = await prisma.screener.findFirst({
where: {
email,
active: true
}
});
const passwordValid = screener && await verifyPassword(password, screener.password);
if (!screener || !passwordValid) {
logger.warn(`Invalid email (${email}) or password`);
throw new AuthenticationError("Invalid email or password");
}
await loginAsUser(userForScreener(screener), context);
return true;
}
Example #6
Source File: author.resolver.ts From mikro-orm-graphql-example with MIT License | 6 votes |
@Query(() => Author, { nullable: true })
public async getAuthor(
@Arg('id') id: string,
@Ctx() ctx: MyContext,
@Info() info: GraphQLResolveInfo,
): Promise<Author | null> {
const relationPaths = fieldsToRelations(info);
return ctx.em.getRepository(Author).findOne({ id }, relationPaths);
}
Example #7
Source File: grow.map.resolver.ts From liferay-grow with MIT License | 6 votes |
@Mutation(() => Boolean, { name: 'updateGrowMapOfficeDetails' })
@Authorized()
async updateGrowMapOfficeDetails(
@Arg('data') data: UserDetailBaseInput,
@Ctx() ctx: MyContext,
): Promise<boolean> {
const user = await getUserFromCtxOrFail(ctx, [
...relations,
'growMap.userDetails',
]);
if (!user.growMap) {
throw new Error('Grow Map not exists');
}
await saveUserDetails(data, user.growMap.userDetails);
return true;
}
Example #8
Source File: post.resolver.ts From Cromwell with MIT License | 5 votes |
@Query(() => Post)
async [getOneBySlugPath](@Arg("slug") slug: string, @Ctx() ctx: TGraphQLContext): Promise<Post | undefined> {
const post = this.filterDrafts([await this.repository.getPostBySlug(slug)], ctx)[0];
if (!post) throw new HttpException(`Post ${slug} not found!`, HttpStatus.NOT_FOUND);
return post;
}
Example #9
Source File: invitation-resolver.ts From convoychat with GNU General Public License v3.0 | 5 votes |
@Authorized()
@UseMiddleware(RateLimit({ limit: 15 }))
@Mutation(() => [Invitation])
async inviteMembers(
@Args() { roomId, members }: inviteMembersArgs,
@Ctx() context: Context
) {
try {
// check if user is a memeber of the specified room
const user = await UserModel.findOne({
_id: context.currentUser.id,
rooms: { $in: [roomId] },
});
if (!user) {
throw new ApolloError(
"You are not a member of room, Cannot invite members"
);
}
let token = null;
// create invitations
const invitations = members.map(memberId => {
token = crypto.randomBytes(16).toString("hex");
const invite = new InvitationModel({
roomId: roomId,
userId: memberId,
invitedBy: context.currentUser.id,
token: token,
});
return invite.save();
});
// @ts-ignore
const savedInvites: Invitation[] = await Promise.all(invitations);
const foundRoom = await RoomModel.findOne({ _id: roomId });
// send notification
const notifications = members.map(async (id, index) => {
return sendNotification({
context: context,
sender: context.currentUser.id,
receiver: id,
type: NOTIFICATION_TYPE.INVITATION,
payload: {
userId: id,
roomName: foundRoom.name,
roomId: roomId,
invitedBy: context.currentUser.id,
token: savedInvites[index].token,
},
});
});
await Promise.all(notifications);
// TODO: Send Email invitations
return savedInvites;
} catch (err) {
console.log(err);
throw new ApolloError(err);
}
}
Example #10
Source File: post.ts From lireddit with MIT License | 5 votes |
@FieldResolver(() => User)
creator(@Root() post: Post, @Ctx() { userLoader }: MyContext) {
return userLoader.load(post.creatorId);
}
Example #11
Source File: Comment.resolver.ts From bouncecode-cms with GNU General Public License v3.0 | 5 votes |
@Mutation(() => Number)
async commentDelete(
@Arg('where') where: CommentUniqueWhereInput,
@Ctx() ctx: Context,
) {
try {
const userId = ctx.user.id;
const comment = await getRepository(CommentEntity)
.createQueryBuilder('comment')
.leftJoinAndSelect('comment.user', 'user')
.getOne();
const postId = comment.postId;
if (comment.user.id !== userId) {
throw new ApolloError('권한이 없습니다.');
}
const affected = await getConnection().transaction(
async transactionalEntityManager => {
const queryBuilder = await getConnection()
.createQueryBuilder()
.delete()
.from(CommentEntity)
.where('id = :id', {id: where.id})
.execute();
await transactionalEntityManager
.createQueryBuilder()
.update(CommentStatEntity)
.set({
count: () => 'count - 1',
})
.where('postId = :postId', {postId: postId})
.execute();
return queryBuilder.affected;
},
);
return affected;
} catch (e) {
console.log(e);
return new ApolloError(e);
}
}
Example #12
Source File: authentication.ts From backend with MIT License | 5 votes |
@Authorized(Role.UNAUTHENTICATED)
@Mutation(returns => Boolean)
@Deprecated("use loginPassword or loginToken instead")
async loginLegacy(@Ctx() context: GraphQLContext, @Arg("authToken") authToken: string) {
ensureSession(context);
const logger = logInContext(`GraphQL Authentication`, context);
const pupil = await prisma.pupil.findFirst({
where: {
// This drops support for unhashed tokens as present in the REST authentication
authToken: hashToken(authToken),
active: true
}
});
if (pupil) {
if (!pupil.verifiedAt) {
/* Previously there was an extra database field for verifying the E-Mail.
I do not see the purpose of that, as presenting a valid authToken is also proof that the account exists.
This can co-exist with the current "verification" implementation.
TODO: Drop the verification column once we moved to GraphQL on the frontend */
logger.info(`Pupil(${pupil.id}) did not verify their e-mail yet, but presented legacy token (thus proved their ownership)`);
await prisma.pupil.update({
data: {
verification: null,
verifiedAt: new Date()
},
where: { id: pupil.id }
});
}
await loginAsUser(userForPupil(pupil), context);
return true;
}
const student = await prisma.student.findFirst({
where: {
authToken: hashToken(authToken),
active: true
}
});
if (student) {
if (!student.verifiedAt) {
/* Previously there was an extra database field for verifying the E-Mail.
I do not see the purpose of that, as presenting a valid authToken is also proof that the account exists.
This can co-exist with the current "verification" implementation.
TODO: Drop the verification column once we moved to GraphQL on the frontend */
logger.info(`Student(${student.id}) did not verify their e-mail yet, but presented legacy token (thus proved their ownership)`);
await prisma.student.update({
data: {
verification: null,
verifiedAt: new Date()
},
where: { id: student.id }
});
}
await loginAsUser(userForStudent(student), context);
return true;
}
logger.warn(`Invalid authToken`);
throw new AuthenticationError("Invalid authToken");
}