Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Resolver, Query, Ctx, Mutation, Arg, FieldResolver, Root } from "type-graphql";
import { User, RegisterInput } from '../entities/User';
import * as crypto from "crypto-js";
import { File } from "../entities/File";
import { GraphQLUpload } from 'graphql-upload';
import { createWriteStream } from "fs";
@Resolver(User)
export class UserResolver {
// Query - Users
@Query(returns => [User])
allUsers() {
return User.find();
}
// Field Resolver Örnek
@FieldResolver()
async name(@Root() parent: User) {
return `${parent.firstName + ' ' + parent.lastName}`;
}
// Mutation - login
@Mutation(returns => User, { nullable: true })
async login(
@Arg('userName') userName: string,
@Arg('password') password: string,
@Ctx() context: any,
): Promise<User> {
const user = await User.findOne({ userName });
const hashedPassword = crypto.SHA256(password).toString();
console.log(user)
if (!user) {
throw new Error('bad credentials'); // it is inconvenient to show which one is wrong because it is sensitive.
}
else if (user.password !== hashedPassword) {
throw new Error('bad credentials'); // it is inconvenient to show which one is wrong because it is sensitive.
}
else {
context.session.userId = user.id;
console.log(user.id);
return user;
}
}
// Query - me
@Query(returns => User)
async me(
@Ctx() context: any
) {
const userId = context.session.userId;
if (userId) {
const user = await User.findOne({ id: userId });
return user;
} else {
throw new Error('not logged in');
}
}
// Mutation - register
@Mutation(returns => User)
async register(@Arg('newUser') registerInput: RegisterInput): Promise<RegisterInput> {
// my validations
const userCheck = await User.findOne({ where: { username: registerInput.userName } });
if (userCheck.userName === registerInput.userName) {
throw new Error('username has already been used.');
}
if (userCheck.email === registerInput.email) {
throw new Error('email has already been used.')
}
if (userCheck.slug === registerInput.slug) {
throw new Error('username has already been used.')
}
const newUser = new User();
const hashedPassword = crypto.SHA256(registerInput.password).toString();
newUser.userName = registerInput.userName;
newUser.email = registerInput.email;
newUser.slug = registerInput.slug;
newUser.password = hashedPassword;
newUser.firstName = registerInput.firstName;
newUser.lastName = registerInput.lastName;
newUser.role = registerInput.role;
await newUser.save();
return newUser;
}
// Mutation - ImageUpload
@Mutation(returns => Boolean)
async imageUpload(@Arg('file', () => GraphQLUpload) file: File) {
const { filename, mimetype, createReadStream } = await file;
const stream = createReadStream();
stream.pipe(createWriteStream(filename));
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment