Skip to content

Instantly share code, notes, and snippets.

@vinodchauhan7
Created November 10, 2019 12:39
Show Gist options
  • Save vinodchauhan7/e3f0322182768ad29f602782d37a3574 to your computer and use it in GitHub Desktop.
Save vinodchauhan7/e3f0322182768ad29f602782d37a3574 to your computer and use it in GitHub Desktop.
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";
import { ObjectType, Field, ID } from "type-graphql";
@ObjectType()
@Entity()
export class User extends BaseEntity {
@Field(() => ID)
@PrimaryGeneratedColumn()
id: number;
@Field()
@Column("text", { nullable: true })
name: string;
@Field()
@Column("text", { nullable: true })
email: string;
@Column("text", { nullable: true })
password: string;
}
import {
Resolver,
Query,
Mutation,
Arg,
ObjectType,
Field
} from "type-graphql";
import { hash, compare } from "bcryptjs";
import { User } from "./entity/User";
@ObjectType()
class LoginResponse {
@Field()
accessToken: string;
}
@Resolver()
export class UserResolver {
@Query(() => String)
async hello() {
return "Hello World";
}
@Query(() => [User])
async getUsers() {
return await User.find();
}
@Mutation(() => Boolean)
async Register(
@Arg("name") name: string,
@Arg("email") email: string,
@Arg("password") password: string
) {
const hashedPassword = await hash(password, 13);
// let user = null;
try {
await User.insert({
name,
email,
password: hashedPassword
});
} catch (err) {
console.log(err);
return false;
}
return true;
}
@Mutation(() => LoginResponse)
async Login(@Arg("email") email: string, @Arg("password") password: string) {
const user = await User.findOne({ where: { email } });
if (!user) {
throw new Error("Could not find user");
}
const verify = compare(password, user.password);
if (!verify) {
throw new Error("Bad password");
}
return {
accessToken: "jhfksjhdk"
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment