Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DRAFT - 111 ajout dune table group #117

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions backend/src/config/db.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import {DataSource} from "typeorm";
import {User} from "../entity/User";
import {SavedQuery} from "../entity/SavedQuery";
import {Log} from "../entity/Log";
import * as dotenv from 'dotenv';
import { DataSource } from "typeorm";
import { User } from "../entity/User";
import { SavedQuery } from "../entity/SavedQuery";
import { Log } from "../entity/Log";
import * as dotenv from "dotenv";
import { Group } from "../entity/Group";

dotenv.config();

const isProd = process.env.NODE_ENV === "production";
const databaseHost = isProd
? process.env.DATABASE_HOST_PROD
: process.env.DATABASE_HOST_DEV;

export const dataSource = new DataSource({
type: "postgres",
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT!),
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
synchronize: true,
logging: ["error", "query"],
entities: [User, SavedQuery, Log],
type: "postgres",
host: databaseHost,
port: parseInt(process.env.DATABASE_PORT!),
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
synchronize: true,
logging: ["error", "query"],
entities: [User, SavedQuery, Log, Group],
});
31 changes: 31 additions & 0 deletions backend/src/entity/Group.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
BaseEntity,
ManyToMany,
JoinTable,
OneToMany,
} from "typeorm";
import { ObjectType, Field, Int } from "type-graphql";
import { User } from "./User";
import { SavedQuery } from "./SavedQuery";

@ObjectType()
@Entity()
export class Group extends BaseEntity {
@Field(() => Int)
@PrimaryGeneratedColumn()
_id: number;

@Field()
@Column({ type: "varchar", length: 100, unique: true })
name: string;

@ManyToMany(() => User, (user) => user.group)
@JoinTable()
users: User[];

@OneToMany(() => SavedQuery, (query) => query.group)
queries?: SavedQuery[];
}
10 changes: 7 additions & 3 deletions backend/src/entity/SavedQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { ObjectType, Field, Int } from "type-graphql";
import { User } from "./User";
import { Log } from "./Log";
import { Group } from "./Group";

@ObjectType()
@Entity()
Expand All @@ -27,9 +28,6 @@ export class SavedQuery extends BaseEntity {
@Column({ type: "varchar", length: 30 })
name: string;

@ManyToOne(() => User, (user) => user.queries)
user: User;

@Field()
@CreateDateColumn()
createdAt: Date;
Expand All @@ -46,6 +44,12 @@ export class SavedQuery extends BaseEntity {
@Column({ default: 1 })
queryOrder: number;

@ManyToOne(() => User, (user) => user.queries, { nullable: true })
user?: User;

@ManyToOne(() => Group, (group) => group.queries, { nullable: true })
group?: Group;

@OneToMany(() => Log, (log) => log.query)
logs: Log[];
}
51 changes: 31 additions & 20 deletions backend/src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,41 @@
import {Entity, PrimaryGeneratedColumn, Column, OneToMany, BaseEntity} from 'typeorm';
import { ObjectType, Field, Int } from 'type-graphql';
import { SavedQuery } from './SavedQuery';
import {
Entity,
PrimaryGeneratedColumn,
Column,
OneToMany,
BaseEntity,
ManyToMany,
} from "typeorm";
import { ObjectType, Field, Int } from "type-graphql";
import { SavedQuery } from "./SavedQuery";
import { Group } from "./Group";

@ObjectType()
@Entity()
export class User extends BaseEntity {
@Field(() => Int)
@PrimaryGeneratedColumn()
_id: number;
@Field(() => Int)
@PrimaryGeneratedColumn()
_id: number;

@Field()
@Column({ type: 'varchar', length: 100, unique: true })
email: string;
@Field()
@Column({ type: "varchar", length: 100, unique: true })
email: string;

@Field()
@Column({ type: 'varchar', length: 20 })
name: string;
@Field()
@Column({ type: "varchar", length: 20 })
name: string;

@Field()
@Column({ type: 'varchar', length: 100 })
password: string;
@Field()
@Column({ type: "varchar", length: 100 })
password: string;

@Field(() => Int)
@Column({ type: 'enum', enum: [0, 1, 2] })
role: number;
@Field(() => Int)
@Column({ type: "enum", enum: [0, 1, 2] })
role: number;

@OneToMany(() => SavedQuery, query => query.user)
queries: SavedQuery[];
@OneToMany(() => SavedQuery, (query) => query.user)
queries?: SavedQuery[];

@ManyToMany(() => Group, (group) => group.users)
group?: Group[];
}
24 changes: 12 additions & 12 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import "dotenv/config";

import "reflect-metadata";
import {dataSource} from "./config/db";
import {buildSchema} from "type-graphql";
import { dataSource } from "./config/db";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from '@apollo/server/standalone';
import { startStandaloneServer } from "@apollo/server/standalone";
import UserResolver from "./resolvers/UserResolver";
import SavedQueryResolver from "./resolvers/SavedQueryResolver";
import LogResolver from "./resolvers/LogResolver";
import PaymentResolver from "./resolvers/PaymentResolver";
import jwt from "jsonwebtoken";
import cookie from "cookie";
import { startSavedQueriesWorker } from './workers/savedQueriesWorker';
import { startSavedQueriesWorker } from "./workers/savedQueriesWorker";
import GroupResolver from "./resolvers/GroupResolver";

const start = async () => {

await dataSource.initialize();

const schema = await buildSchema({
resolvers: [UserResolver, SavedQueryResolver, LogResolver, PaymentResolver],
authChecker: ({context}, roles) => {
resolvers: [UserResolver, SavedQueryResolver, LogResolver, GroupResolver],
authChecker: ({ context }, roles) => {
// Check user
if (!context.email) {
// No user, restrict access
Expand All @@ -34,10 +34,10 @@ const start = async () => {

// Check '@Authorized(...)' roles includes the role of user
return roles.includes(context.role);
}
},
});

const server = new ApolloServer({schema});
const server = new ApolloServer({ schema });

// Passing an ApolloServer instance to the `startStandaloneServer` function:
await startStandaloneServer(server, {
Expand All @@ -51,8 +51,8 @@ const start = async () => {

if (cookies.token) {
const payload = jwt.verify(
cookies.token,
process.env.JWT_SECRET_KEY
cookies.token,
process.env.JWT_SECRET_KEY
) as jwt.JwtPayload;

if (payload) {
Expand All @@ -67,6 +67,6 @@ const start = async () => {
await startSavedQueriesWorker();

console.log(`🚀 Server ready at: http://localhost:7001/api`);
}
};

start();
124 changes: 124 additions & 0 deletions backend/src/resolvers/GroupResolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import "dotenv/config";
import { Resolver, Mutation, Arg, Query } from "type-graphql";
import { User } from "../entity/User";
import { Group } from "../entity/Group";
import { In } from "typeorm";

@Resolver()
class GroupResolver {
// Create Group
@Mutation(() => String)
async createGroup(
@Arg("name", () => String) name: string,
@Arg("emails", () => [String]) emails: string[]
): Promise<String> {
// Vérifier si le groupe existe déjà
const groupExists = await Group.findOne({ where: { name: name } });
if (groupExists) {
throw new Error("Group name already used");
}

// Rechercher les utilisateurs correspondant aux emails fournis
const users = await User.find({
where: {
email: In(emails),
},
});
const foundEmails = users.map((user) => user.email);
const notFoundEmails = emails.filter(
(email) => !foundEmails.includes(email)
);

if (notFoundEmails.length > 0) {
throw new Error(
`Users with the following emails not found: ${notFoundEmails.join(
", "
)}`
);
}

// Créer le groupe avec les utilisateurs trouvés
const group = Group.create({
name: name,
users: users,
});
await group.save();
return "Group created";
}

// Read Groups
@Query(() => [Group])
async getGroups(): Promise<Group[]> {
return await Group.find({ relations: ["users"] });
}

@Query(() => Group, { nullable: true })
async getGroupById(
@Arg("id", () => String) id: string
): Promise<Group | null> {
const group = await Group.findOne({
where: { id },
relations: ["users"],
});
if (!group) {
throw new Error(`Group with id ${id} not found`);
}
return group;
}

// Update Group
@Mutation(() => String)
async updateGroup(
@Arg("id", () => String) id: string,
@Arg("name", () => String, { nullable: true }) name?: string,
@Arg("emails", () => [String], { nullable: true }) emails?: string[]
): Promise<String> {
const group = await Group.findOne({ where: { id }, relations: ["users"] });
if (!group) {
throw new Error("Group not found");
}

if (name) {
group.name = name;
}

if (emails) {
const users = await User.find({
where: {
email: In(emails),
},
});
const foundEmails = users.map((user) => user.email);
const notFoundEmails = emails.filter(
(email) => !foundEmails.includes(email)
);

if (notFoundEmails.length > 0) {
throw new Error(
`Users with the following emails not found: ${notFoundEmails.join(
", "
)}`
);
}

group.users = users;
}

await group.save();
return "Group updated";
}

// Delete Group
@Mutation(() => String)
async deleteGroup(@Arg("id", () => String) id: string): Promise<String> {
const group = await Group.findOne({ where: { id } });
if (!group) {
throw new Error("Group not found");
}

await group.remove();
return "Group deleted";
}
}

export default GroupResolver;
Loading