Add user service and implements for internal functions and exports#

This commit is contained in:
Sambo Chea 2021-03-13 10:37:40 +07:00
parent 7b4b438b31
commit fc4d8c9cdb
3 changed files with 110 additions and 28 deletions

94
src/User/UserService.ts Normal file
View File

@ -0,0 +1,94 @@
import { PrismaClient, User } from "@prisma/client";
const prisma = new PrismaClient();
async function isProfileExistByEmail(email: string) {
const exist = await prisma.profile.count({
where: {
user: {
email: email,
},
},
});
return exist > 0;
}
async function findOneProfileByEmail(email: string) {
const profile = await prisma.profile.findFirst({
where: {
user: {
email: email,
},
},
});
return profile;
}
async function isExistByEmail(email: string) {
const exist = await prisma.user.count({
where: {
email: email,
},
});
return exist > 0;
}
async function findOneByEmail(
email: string,
throwableIfNotFound: boolean = false
) {
const user = await prisma.user.findFirst({
where: {
email: email,
},
});
if (user == null && throwableIfNotFound) {
throw Error(`user not found by email: ${email}!`);
}
return user;
}
async function createUser() {
const email = "ops@cubetiqs.com";
if (isExistByEmail(email)) {
console.log("User existed with email => ", email);
return findOneByEmail(email);
}
const user = await prisma.user.create({
data: {
name: "CUBETIQ Solution",
email: email,
},
});
console.log("User created => ", user);
return user;
}
async function createProfile(user: User) {
if (isProfileExistByEmail(user.email)) {
console.log("Profile existed by email => ", user.email);
return findOneProfileByEmail(user.email);
}
const profile = await prisma.profile.create({
data: {
userId: user.id,
bio: "Software Company",
},
});
console.log("Profile created => ", profile);
return profile;
}
export { createUser, createProfile };

View File

@ -1,14 +1,17 @@
import { PrismaClient, User } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import { createUser, createProfile } from "./User/UserService";
const prisma = new PrismaClient();
// A `main` function so that you can use async/await
// main function
async function main() {
// create user
await createUser()
.then((user) => {
if (user != null) {
// create profile for user
createProfile(user);
}
})
.catch((e) => {
console.error(e);
@ -18,30 +21,6 @@ async function main() {
console.log("All users => ", allUsers);
}
async function createUser() {
const user = await prisma.user.create({
data: {
name: "CUBETIQ Solution",
email: "ops@cubetiqs.com",
},
});
console.log("User => ", user);
return user;
}
async function createProfile(user: User) {
const profile = await prisma.profile.create({
data: {
userId: user.id,
bio: "Software Company",
},
});
console.log("Profile => ", profile);
}
main()
.catch((e) => {
throw e;

9
test/user.test.ts Normal file
View File

@ -0,0 +1,9 @@
describe('user', function() {
it('createUser', function() {
})
it('checkUser', function() {
})
})