typeorm#ObjectType TypeScript Examples

The following examples show how to use typeorm#ObjectType. 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: entity.ts    From typeorm-extension with MIT License 6 votes vote down vote up
export function getEntityName<O>(entity: ObjectType<O> | EntitySchema<O>) : string {
    if (typeof entity === 'function') {
        return entity.name;
    }

    if (InstanceChecker.isEntitySchema(entity)) {
        return entity.options.name;
    }

    return new (entity as any)().constructor.name;
}
Example #2
Source File: utils.ts    From typeorm-extension with MIT License 6 votes vote down vote up
export function useSeederFactory<O extends Record<string, any>>(
    entity: ObjectType<O> | EntitySchema<O>,
) {
    const manager = useSeederFactoryManager();
    return manager.get(entity);
}
Example #3
Source File: utils.ts    From typeorm-extension with MIT License 6 votes vote down vote up
export function setSeederFactory<O extends Record<string, any>>(
    entity: ObjectType<O> | EntitySchema<O>,
    factoryFn: FactoryCallback<O>,
) : SeederFactoryConfig {
    const manager = useSeederFactoryManager();
    return manager.set(entity, factoryFn);
}
Example #4
Source File: manager.ts    From typeorm-extension with MIT License 6 votes vote down vote up
get<O extends Record<string, any>>(
        entity: ObjectType<O> | EntitySchema<O>,
    ) : SeederFactory<O> {
        const name = getEntityName(entity);

        if (!hasOwnProperty(this.items, name)) {
            throw new Error(`No seeder factory is registered for the entity: ${name}`);
        }

        return new SeederFactory({
            factoryFn: this.items[name].factoryFn,
            entity,
            name,
        });
    }
Example #5
Source File: manager.ts    From typeorm-extension with MIT License 6 votes vote down vote up
set<O extends Record<string, any>>(
        entity: ObjectType<O> | EntitySchema<O>,
        factoryFn: FactoryCallback<O>,
    ) : SeederFactoryConfig {
        const name = getEntityName(entity);

        this.items[name] = {
            factoryFn,
            entity,
        };

        return this.items[name];
    }
Example #6
Source File: TypeormLoader.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
export function TypeormLoader<V>(
  typeFuncOrKeyFunc?: ((type?: void) => ObjectType<V>) | KeyFunc,
  keyFuncOrOption?: KeyFunc | TypeormLoaderOption,
  option?: TypeormLoaderOption
): PropertyDecorator {
  if (typeFuncOrKeyFunc == null) {
    return ImplicitLoaderImpl();
  }

  const getArgs = (): [KeyFunc, TypeormLoaderOption | undefined] => {
    return option != null || typeof keyFuncOrOption == "function"
      ? [keyFuncOrOption as KeyFunc, option]
      : [typeFuncOrKeyFunc as KeyFunc, keyFuncOrOption as TypeormLoaderOption];
  };
  return ExplicitLoaderImpl<V>(...getArgs());
}
Example #7
Source File: database.service.ts    From rest-api.ts with MIT License 5 votes vote down vote up
public async getRepository<T>(repository: ObjectType<T>): Promise<T> {
    const connection = await this.getConnection();
    return await connection.getCustomRepository<T>(repository);
  }
Example #8
Source File: repository.ts    From advanced-node with GNU General Public License v3.0 5 votes vote down vote up
getRepository<Entity> (entity: ObjectType<Entity>): Repository<Entity> {
    return this.connection.getRepository(entity)
  }
Example #9
Source File: connection.ts    From advanced-node with GNU General Public License v3.0 5 votes vote down vote up
getRepository<Entity> (entity: ObjectType<Entity>): Repository<Entity> {
    if (this.connection === undefined) throw new ConnectionNotFoundError()
    if (this.query !== undefined) return this.query.manager.getRepository(entity)
    return getRepository(entity)
  }
Example #10
Source File: Pagination.ts    From Designer-Server with GNU General Public License v3.0 5 votes vote down vote up
constructor(type: ObjectType<T>, connection: Connection) {
    this.type = type;
  }
Example #11
Source File: index.ts    From backend with MIT License 5 votes vote down vote up
async function putProjectFields(wix_id: string, req: ApiProjectFieldInfo[], person: Pupil | Student): Promise<number> {
    const entityManager = getManager();
    const transactionLog = getTransactionLog();

    if (person == null) {
        logger.error("getUser() returned null");
        return 500;
    }
    if (person.wix_id != wix_id) {
        logger.warn("Person with id " + person.wix_id + "tried to access data from id " + wix_id);
        return 403;
    }

    //check if the person is a project coach(ee), otherwise do not allow setting project fields
    if (!(person as Pupil).isProjectCoachee && !(person as Student).isProjectCoach) {
        logger.error(`Person with id ${person.wix_id} is no project coach(ee) and thus setting project fields is invalid!`);
        return 400;
    }

    let oldProjectFields: ProjectFieldWithGradeInfoType[];

    const projectFields = req as ProjectFieldWithGradeInfoType[];
    let type: ObjectType<Person>;
    if (person instanceof Student) {
        oldProjectFields = await person.getProjectFields();
        await person.setProjectFields(projectFields);
    } else if (person instanceof Pupil) {
        oldProjectFields = person.projectFields.map(p => ({name: p}));
        person.projectFields = projectFields.map(pf => pf.name);
    } else {
        logger.error("Unknown type of person: " + typeof person);
        logger.debug(person);
        return 500;
    }

    try {
        await entityManager.save(person);
        await transactionLog.log(
            new UpdateProjectFieldsEvent(person, oldProjectFields)
        );
    } catch (e) {
        logger.error("Can't update " + type.toString() + ": " + e.message);
        logger.debug(person, e);
    }

    return 204;
}
Example #12
Source File: index.ts    From backend with MIT License 5 votes vote down vote up
async function putSubjects(wix_id: string, req: ApiSubject[], person: Pupil | Student): Promise<number> {
    const entityManager = getManager();
    const transactionLog = getTransactionLog();

    if (person == null) {
        logger.error("getUser() returned null");
        return 500;
    }
    if (person.wix_id != wix_id) {
        logger.warn("Person with id " + person.wix_id + "tried to access data from id " + wix_id);
        return 403;
    }

    const oldPerson = Object.assign({}, person);

    let type: ObjectType<Person>;
    if (person instanceof Student) {

        type = Student;
        if (!person.isStudent) {
            person.isStudent = true;
        }

    } else if (person instanceof Pupil) {

        type = Pupil;
        if (!person.isPupil) {
            person.isPupil = true;
        }

    } else {
        logger.error("Unknown type of person: " + typeof person);
        logger.debug(person);
        return 500;
    }

    person.subjects = JSON.stringify(req);

    // if (person instanceof Student &&
    //     person.isCodu &&
    //     !checkCoDuSubjectRequirements(person.getSubjectsFormatted())) {
    //     logger.warn("Student does not fulfill subject requirements for CoDu");
    //     return 400;
    // }

    try {
        await entityManager.save(type, person);
        await transactionLog.log(
            new UpdateSubjectsEvent(person, JSON.parse(oldPerson.subjects))
        );
    } catch (e) {
        logger.error("Can't update " + type.toString() + ": " + e.message);
        logger.debug(person, e);
    }

    return 204;
}
Example #13
Source File: createQueryBuilder.ts    From typeorm-cursor-pagination with MIT License 5 votes vote down vote up
export function createQueryBuilder<T>(entity: ObjectType<T>, alias: string): SelectQueryBuilder<T> {
  return getConnection()
    .getRepository(entity)
    .createQueryBuilder(alias);
}
Example #14
Source File: Paginator.ts    From typeorm-cursor-pagination with MIT License 5 votes vote down vote up
public constructor(
    private entity: ObjectType<Entity>,
    private paginationKeys: Extract<keyof Entity, string>[],
    private paginationUniqueKey: Extract<keyof Entity, string>,
  ) {}
Example #15
Source File: Pagination.ts    From Designer-Server with GNU General Public License v3.0 5 votes vote down vote up
// private
  private type: ObjectType<T>;
Example #16
Source File: index.ts    From backend with MIT License 4 votes vote down vote up
async function putActive(wix_id: string, active: boolean, person: Pupil | Student, deactivationReason?: string, deactivationFeedback?: string): Promise<number> {
    const entityManager = getManager();
    const transactionLog = getTransactionLog();

    if (person == null) {
        logger.error("getUser() returned null");
        return 500;
    }
    if (person.wix_id != wix_id) {
        logger.warn("Person with id " + person.wix_id + " tried to access data from id " + wix_id);
        return 403;
    }

    let type: ObjectType<Person>;
    if (person instanceof Student) {
        type = Student;
    } else if (person instanceof Pupil) {
        type = Pupil;
    } else {
        logger.error("Unknown type of person: " + typeof person);
        logger.debug(person);
        return 500;
    }

    let debugCancelledCourses = [];
    let debugRemovedFrom = [];

    try {
        if (active && !person.active) {
            // Activate if deactivated
            logger.info("Activating person " + person.firstname + " " + person.lastname);
            person.active = true;

            await entityManager.save(type, person);
            await transactionLog.log(new DeActivateEvent(person, true));
        } else if (!active && person.active) {
            // Deactivate if active
            logger.info("Deactivating person " + person.firstname + " " + person.lastname);
            person.active = false;
            await entityManager.save(type, person);

            // Step 1: Dissolve all matches
            let options;
            if (type == Student) {
                options = {
                    student: person,
                    dissolved: false
                };
            } else {
                options = {
                    pupil: person,
                    dissolved: false
                };
            }
            let matches = await entityManager.find(Match, options);
            for (let i = 0; i < matches.length; i++) {
                await dissolveMatch(matches[i], 0, person);
            }

            // Step 2: Cancel all courses if user is student
            if (type == Student) {
                let courses = await getConnection()
                    .getRepository(Course)
                    .createQueryBuilder("course")
                    .leftJoinAndSelect("course.instructors", "instructors")
                    .innerJoin("course.instructors", "instructorsSelect")
                    .where("instructorsSelect.id = :id", { id: person.id})
                    .leftJoinAndSelect("course.subcourses", "subcourses")
                    .getMany();

                logger.debug("Trying to cancel following courses: ", courses);

                await entityManager.transaction(async em => {
                    for (const course of courses) {
                        logger.debug("Iterating through courses:", "Current course name:", course.name, "Instructors:", course.instructors, "Length of array:", course.instructors.length);
                        if (!course.instructors.some(i => i.id === person.id)) { // Only proceed if we're part of this course as an instructor
                            continue;
                        }

                        if (course.instructors.length > 1) {
                        // Course still has other instructors, only remove our person from those. We don't want to cancel those courses.
                            course.instructors = course.instructors.filter(s => s.id !== person.id);
                            await em.save(Course, course);
                            debugRemovedFrom.push(course);
                        } else {
                        // Our person is the only instructor in the course. Cancel it.
                            for (const subcourse of course.subcourses) {
                                if (!subcourse.cancelled) {
                                    subcourse.cancelled = true;
                                    await em.save(Subcourse, subcourse);
                                    //await sendSubcourseCancelNotifications(course, subcourse);
                                }
                            }

                            course.courseState = CourseState.CANCELLED;
                            await em.save(Course, course);
                            transactionLog.log(new CancelCourseEvent(person as Student, course));
                            debugCancelledCourses.push(course);
                        }

                    }
                });
                logger.info("Courses user was removed from (as an instructor): ", debugRemovedFrom);
                logger.info("Courses that were cancelled (user was the sole instructor): ", debugCancelledCourses);
            }

            await Notification.cancelRemindersFor(person);

            await transactionLog.log(new DeActivateEvent(person, false, deactivationReason, deactivationFeedback));
        }
    } catch (e) {
        logger.error("Can't " + (active ? "" : "de") + "activate user: " + e.message);
        logger.debug(person);
        logger.debug(e);
        return 500;
    }
    return 204;
}
Example #17
Source File: index.ts    From backend with MIT License 4 votes vote down vote up
async function putPersonal(wix_id: string, req: ApiPutUser, person: Pupil | Student | Mentor): Promise<number> {
    const entityManager = getManager();
    const transactionLog = getTransactionLog();

    if (person == null) {
        logger.error("getUser() returned null");
        return 500;
    }
    if (person.wix_id != wix_id) {
        logger.warn("Person with id " + person.wix_id + "tried to access data from id " + wix_id);
        return 403;
    }

    const oldPerson = Object.assign({}, person);

    person.firstname = req.firstname.trim();
    person.lastname = req.lastname.trim();

    if (!checkName(person.firstname) || !checkName(person.lastname)) {
        logger.warn("Invalid names: " + person.firstname + " / " + person.lastname);
    }

    let type: ObjectType<Person>;
    if (person instanceof Student) {
        type = Student;
        // ++++ OPEN MATCH REQUEST COUNT ++++
        // Check if number of requested matches is valid
        let matchCount = await entityManager.count(Match, { student: person, dissolved: false });
        if (req.matchesRequested > 3 || req.matchesRequested < 0 || !Number.isInteger(req.matchesRequested) || req.matchesRequested + matchCount > 6
            || (req.matchesRequested > 1 && await person.screeningStatus() != ScreeningStatus.Accepted && await person.instructorScreeningStatus() != ScreeningStatus.Accepted)) {
            logger.warn("User (with " + matchCount + " matches) wants to set invalid number of matches requested: " + req.matchesRequested);
            return 400;
        }

        person.openMatchRequestCount = req.matchesRequested;

        // ++++ UNIVERSITY ++++
        person.university = req.university;

        // ++++ STATE ++++
        if (req.state) {
            const state = EnumReverseMappings.State(req.state);
            if (!state) {
                logger.warn(`User wants to set an invalid value "${req.state}" for state`);
                return 400;
            }
            person.state = state;
        }

        // ++++ LAST UPDATED SETTINGS VIA BLOCKER ++++
        if (req.lastUpdatedSettingsViaBlocker) {
            person.lastUpdatedSettingsViaBlocker = moment.unix(req.lastUpdatedSettingsViaBlocker).toDate();
        } else {
            person.lastUpdatedSettingsViaBlocker = null;
        }

        // ++++ OPEN _PROJECT_ MATCH REQUEST COUNT ++++
        // Check if number of requested project matches is valid
        if (req.projectMatchesRequested != null) {
            let projectMatchCount = await entityManager.count(ProjectMatch, { student: person, dissolved: false });
            if (req.projectMatchesRequested > 3 || req.projectMatchesRequested < 0 || !Number.isInteger(req.projectMatchesRequested) || req.projectMatchesRequested + projectMatchCount > 6) {
                logger.warn("User (with " + projectMatchCount + " matches) wants to set invalid number of project matches requested: " + req.projectMatchesRequested);
                return 400;
            }
            person.openProjectMatchRequestCount = req.projectMatchesRequested;
        }

        // ++++ DAZ INFORMATION ++++
        if (req.languages) {
            const languages = req.languages.map(l => EnumReverseMappings.Language(l));
            if (!languages.every(l => l)) {
                logger.warn(`User wants to set invalid values "${req.languages}" for languages`);
                return 400;
            }
            person.languages = languages;
        }

        person.supportsInDaZ = req.supportsInDaz;

        // ++++ CODU INFORMATION ++++
        // if (req.isCodu !== undefined) {
        //     if (req.isCodu && !checkCoDuSubjectRequirements(person.getSubjectsFormatted())) {
        //         logger.warn("Student does not fulfill subject requirements for CoDu");
        //         return 400;
        //     }
        //     person.isCodu = req.isCodu;
        // }

    } else if (person instanceof Pupil) {
        type = Pupil;

        // ++++ OPEN MATCH REQUEST COUNT ++++
        // Check if number of requested matches is valid
        if (req.matchesRequested !== undefined && person.openMatchRequestCount !== req.matchesRequested) {
            if (!Number.isInteger(req.matchesRequested) || req.matchesRequested < 0) {
                logger.warn(`While updating Pupil(${person.id}): matchRequested ${req.matchesRequested} is not an integer or below zero`);
                return 400;
            }

            if (req.matchesRequested > 1) {
                // NOTE: Admins can enter a larger number into the database
                logger.warn(`While updating Pupil(${person.id}): Pupils may only have one open match request (requested: ${req.matchesRequested}, current: ${person.openMatchRequestCount})`);
                return 400;
            }

            let matchCount = await entityManager.count(Match, {
                pupil: person,
                dissolved: false
            });

            if (req.matchesRequested > person.openMatchRequestCount && (req.matchesRequested + matchCount) > 1) {
                // NOTE: The opposite scenario can happen when an admin manually increased the match request count. The user can then decrease that number
                logger.warn(`While updating Pupil(${person.id}): Pupils may only request more matches when they do not have a Match already (requested: ${req.matchesRequested}, current: ${person.openMatchRequestCount}, actual: ${matchCount})`);
                return 400;
            }

            person.openMatchRequestCount = req.matchesRequested;
        }

        // ++++ GRADE ++++
        if (Number.isInteger(req.grade) && req.grade >= 1 && req.grade <= 13) {
            person.grade = req.grade + ". Klasse";
        } else {
            logger.warn("User who is a pupil wants to set an invalid grade! It is ignored.");
        }

        // ++++ SCHOOL TYPE ++++
        if (req.schoolType) {
            const schoolType = EnumReverseMappings.SchoolType(req.schoolType);
            if (!schoolType) {
                logger.warn(`User wants to set an invalid value "${req.schoolType}" for schoolType`);
                return 400;
            }
            person.schooltype = schoolType;
        }

        // ++++ STATE ++++
        if (req.state) {
            const state = EnumReverseMappings.State(req.state);
            if (!state) {
                logger.warn(`User wants to set an invalid value "${req.state}" for state`);
                return 400;
            }
            person.state = state;
        }

        // ++++ LAST UPDATED SETTINGS VIA BLOCKER ++++
        if (req.lastUpdatedSettingsViaBlocker) {
            person.lastUpdatedSettingsViaBlocker = moment.unix(req.lastUpdatedSettingsViaBlocker).toDate();
        } else {
            person.lastUpdatedSettingsViaBlocker = null;
        }

        // ++++ OPEN _PROJECT_ MATCH REQUEST COUNT ++++
        // Check if number of requested project matches is valid
        if (req.projectMatchesRequested != null) {
            let projectMatchCount = await entityManager.count(ProjectMatch, { pupil: person, dissolved: false });
            if (req.projectMatchesRequested > 1 || req.projectMatchesRequested < 0 || !Number.isInteger(req.projectMatchesRequested) || req.projectMatchesRequested + projectMatchCount > 1) {
                logger.warn("User (with " + projectMatchCount + " matches) wants to set invalid number of project matches requested: " + req.projectMatchesRequested);
                return 400;
            }
            person.openProjectMatchRequestCount = req.projectMatchesRequested;
        }

        // ++++ DAZ INFORMATION +++++
        if (req.languages) {
            const languages = req.languages.map(l => EnumReverseMappings.Language(l));
            if (!languages.every(l => l)) {
                logger.warn(`User wants to set invalid values "${req.languages}" for languages`);
                return 400;
            }
            person.languages = languages;
        }

        if (req.learningGermanSince) {
            const learningGermanSince = EnumReverseMappings.LearningGermanSince(req.learningGermanSince);
            if (!learningGermanSince) {
                logger.warn(`User wants to set invalid value "${learningGermanSince}" for learningGermanSince`);
                return 400;
            }
            person.learningGermanSince = learningGermanSince;
        }
    } else if (person instanceof Mentor) {
        type = Mentor;

        if (req.division) {
            let division = checkDivisions(req.division);
            if (division === null) {
                return 400;
            }
            person.division = division;
        }

        if (req.expertise) {
            let expertise = checkExpertises(req.expertise);
            if (expertise === null) {
                return 400;
            }
            person.expertise = expertise;
        }

        if (req.subjects) {
            let subjects = checkSubjects(req.subjects);
            if (subjects === null) {
                return 400;
            }
            person.subjects = subjects;
        }

        if (typeof req.teachingExperience === 'boolean') {
            person.teachingExperience = req.teachingExperience;
        } else if (req.teachingExperience !== undefined) {
            return 400;
        }

        if (req.description) {
            person.description = req.description.trim();
        }

    } else {
        logger.warn("Unknown type of person: " + typeof person);
        logger.debug(person);
        return 500;
    }

    try {
        await entityManager.save(type, person);
        await transactionLog.log(new UpdatePersonalEvent(person, oldPerson));
        if (person instanceof Student && req.isCodu) {
            await Notification.actionTaken(person, "codu_student_registration", {});
        }
        logger.info(`Updated user ${person.firstname} ${person.lastname} (ID ${person.wix_id}, Type ${person?.constructor?.name}`);
        logger.debug(person);
    } catch (e) {
        logger.error("Can't update user: " + e.message);
        logger.debug(person, e);
        return 400;
    }

    return 204;
}