typeorm#getRepository TypeScript Examples
The following examples show how to use
typeorm#getRepository.
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: ApiApplicationController.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
@Get("/")
@Security("jwt")
public async get(
@Request() request: exRequest,
@Query('page') page?: number,
@Query('perPage') perPage?: number
):Promise<any>{
const appRepo = getRepository(Application);
page = page || 1;
perPage = perPage || 10;
const findOptions:FindManyOptions = {
where: {
userId: request.user.id
},
take: perPage,
skip: (page - 1) * perPage
}
const apps = await appRepo.findAndCount(findOptions);
return Promise.resolve({
apps: apps[0],
page,
perPage,
totalCount: apps[1]
});
}
Example #2
Source File: CreateTransactionService.ts From rocketseat-gostack-11-desafios with MIT License | 6 votes |
public async execute({
title,
value,
type,
category,
}: Request): Promise<Transaction> {
const transactionsRepository = getCustomRepository(TransactionsRepository);
const categoryRepository = getRepository(Category);
if (type === 'outcome') {
const { total } = await transactionsRepository.getBalance();
if (value > total) {
throw new AppError('Value for outcome is bigger than total value');
}
}
let categoryExists = await categoryRepository.findOne({
where: { title: category },
});
if (!categoryExists) {
categoryExists = categoryRepository.create({ title: category });
await categoryRepository.save(categoryExists);
}
const transaction = transactionsRepository.create({
title,
value,
type,
category_id: categoryExists.id,
});
await transactionsRepository.save(transaction);
return transaction;
}
Example #3
Source File: class.routes.ts From Project-template-TS with Apache License 2.0 | 6 votes |
classRouter.post('/', async (request, response) => {
try {
const repo = getRepository(Class);
const res = await repo.save(request.body);
return response.status(201).json(res);
} catch (err) {
console.log('err.message :>> ', err.message);
}
});
Example #4
Source File: content.routes.ts From Typescript_TypeORM with Apache License 2.0 | 6 votes |
contentRouter.post('/', async (request, response) => {
try {
const repo = getRepository(Content);
const res = await repo.save(request.body);
return response.status(201).json(res);
} catch (err) {
console.log('err.message :>> ', err.message);
return response.status(400).send();
}
});
Example #5
Source File: ChatRoom.resolver.ts From bouncecode-cms with GNU General Public License v3.0 | 6 votes |
@Query(() => [ChatRoomObject])
async chatRooms(
@Arg('where') where: ChatRoomWhereInput,
@Arg('skip', {nullable: true}) skip: number = 0,
@Arg('take', {nullable: true}) take: number = 10,
@Ctx() ctx: Context,
) {
const userId = ctx.user.id;
const queryBuilder = getRepository(UserEntity)
.createQueryBuilder('user')
.leftJoinAndSelect('user.chatRooms', 'chatRooms')
.andWhere('user.id = :userId', {
userId: userId,
});
if (where.category) {
queryBuilder
.leftJoinAndSelect('chatRooms.category', 'category')
.andWhere('category.id = :categoryId', {
categoryId: where.category,
});
}
const result = await queryBuilder
.offset(skip)
.limit(take)
.getMany();
console.log(result);
return result;
}
Example #6
Source File: AuthController.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 6 votes |
static login = async (req: Request, res: Response) => {
//Check if username and password are set
let { username, password } = req.body;
if (!(username && password)) {
res.status(400).send();
return;
}
//Get user from database
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail({ where: { username } });
} catch (error) {
res.status(401).send();
return;
}
//Check if encrypted password match
if (!user.checkIfUnencryptedPasswordIsValid(password)) {
res.status(401).send();
return;
}
//Sing JWT, valid for 1 hour
const token = jwt.sign({ userId: user.id, username: user.name }, config.jwtSecret, { expiresIn: "1h" });
//Send the jwt in the response
res.send(token);
};
Example #7
Source File: AuthController.ts From mysql_node_angular with MIT License | 6 votes |
static login = async (req: Request, res: Response) => {
const { username, password } = req.body;
if (!(username && password)) {
return res.status(400).json({ message: ' Username & Password are required!' });
}
const userRepository = getRepository(Users);
let user: Users;
try {
user = await userRepository.findOneOrFail({ where: { username } });
} catch (e) {
return res.status(400).json({ message: ' Username or password incorecct!' });
}
// Check password
if (!user.checkPassword(password)) {
return res.status(400).json({ message: 'Username or Password are incorrect!' });
}
const token = jwt.sign({ userId: user.id, username: user.username }, config.jwtSecret, { expiresIn: '1h' });
res.json({ message: 'OK', token, userId: user.id, role: user.role });
};
Example #8
Source File: db.ts From gear-js with GNU General Public License v3.0 | 6 votes |
async connect() {
this.connection = await createConnection({
type: 'postgres',
host: config.db.host,
port: config.db.port,
database: config.db.name,
username: config.db.user,
password: config.db.password,
entities: [TransferBalance],
synchronize: true,
});
this.repo = getRepository(TransferBalance);
log.info('Connected to database');
}
Example #9
Source File: 1614781963810-SeedKnowledgeArea.ts From liferay-grow with MIT License | 6 votes |
public async up(): Promise<void> {
const skillPromises = [];
for (const areaSeed of KnowledgeAreaSeed) {
const { name, skills } = areaSeed;
const area = await getRepository('knowledge_area').save({
name,
skills,
});
for (const skill of skills) {
skillPromises.push(
getRepository('knowledge_skill').save({
area,
createdBy: 'SYSTEM',
description: skill.description,
name: skill.name,
slug: slugify(skill.name),
}),
);
}
}
await Promise.all(skillPromises);
}
Example #10
Source File: connection.spec.ts From advanced-node with GNU General Public License v3.0 | 6 votes |
jest.mock('typeorm', () => ({
Entity: jest.fn(),
PrimaryGeneratedColumn: jest.fn(),
Column: jest.fn(),
createConnection: jest.fn(),
getConnection: jest.fn(),
getConnectionManager: jest.fn(),
getRepository: jest.fn()
}))
Example #11
Source File: CompanyResolver.ts From type-graphql-dataloader with MIT License | 6 votes |
@FieldResolver()
@Loader<string, Chair[]>(async (ids) => {
const chairs = await getRepository(Chair).find({
where: { company: { id: In([...ids]) } },
});
const chairsById = groupBy(chairs, "companyId");
return ids.map((id) => chairsById[id] ?? []);
})
chairs(@Root() root: Company) {
return (dataloader: DataLoader<string, Chair[]>) =>
dataloader.load(root.id);
}
Example #12
Source File: team.controller.ts From bulwark with MIT License | 6 votes |
getAllTeams = async (req: Request, res: Response) => {
const teams = await getConnection()
.getRepository(Team)
.createQueryBuilder('team')
.leftJoinAndSelect('team.users', 'users')
.leftJoinAndSelect('team.assets', 'assets')
.leftJoinAndSelect('team.organization', 'organization')
.select([
'team',
'assets',
'organization',
'users.firstName',
'users.lastName',
'users.title',
'users.id',
])
.getMany();
return res.status(200).json(teams);
}
Example #13
Source File: fixtures-loader.service.ts From nestjs-oauth2-server-module with MIT License | 6 votes |
loadFixtures = async (fixturesPath: string) => {
try {
const loader = new Loader();
loader.load(path.resolve(fixturesPath));
const resolver = new Resolver();
const fixtures = resolver.resolve(loader.fixtureConfigs);
const builder = new Builder(this.connection, new Parser());
for (const fixture of fixturesIterator(fixtures)) {
const entity: any = await builder.build(fixture);
await getRepository(entity.constructor.name).save(entity);
}
} catch (err) {
console.log(err);
throw err;
}
};
Example #14
Source File: ApiMetaController.ts From Designer-Server with GNU General Public License v3.0 | 5 votes |
/**
* database 연결 정보를 이용하여 DB 데이터를 불러오기 위한 Meta 를 등록합니다.
*
* @param request
* @param dbmsParams Meta title과 DB 연결 정보, stageId</br> 지원 dbms: "mysql"|"cubrid"
*/
@Post("/dbms")
@Security("jwt")
public async postDbms(
@Request() request: exRequest,
@Body() dbmsParams: DbmsParams
): Promise<Meta> {
const metaRepo = getRepository(Meta);
const stageRepo = getRepository(Stage);
const { title, dbms, host, port, database, user, password, table, stageId } = dbmsParams;
if(title.length == 0
|| dbms.length == 0
|| host.length == 0
|| port.length == 0
|| database.length == 0
|| user.length == 0
|| table.length == 0) {
throw new ApplicationError(400, ERROR_CODE.META.NEED_ALL_PARAM);
}
const stage = await stageRepo.findOne({
where: {
id: stageId,
userId: request.user.id
}
});
if(!stage) {throw new ApplicationError(404, ERROR_CODE.STAGE.STAGE_NOT_FOUND)}
const queryRunner = await getConnection().createQueryRunner()
const meta: Meta = new Meta();
meta.dataType = 'dbms';
meta.dbms = dbms;
meta.dbUser = user;
meta.pwd = password;
meta.host = host;
meta.port = port;
meta.db = database;
meta.table = table;
meta.title = title;
meta.stageId = stage.id;
meta.userId = request.user.id;
meta.status = MetaStatus.METALOAD_SCHEDULED;
await queryRunner.startTransaction();
try {
await queryRunner.manager.save(meta);
BullManager.Instance.setMetaLoaderSchedule(meta.id);
await queryRunner.commitTransaction();
} catch(err) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
this.setStatus(201);
return Promise.resolve(meta);
}
Example #15
Source File: BaseSqlRepository.ts From node-experience with MIT License | 5 votes |
constructor(@unmanaged() entityName: string, @unmanaged() schema: EntitySchema)
{
this.entityName = entityName;
this.repository = getRepository<T>(schema);
}
Example #16
Source File: AppointmentsRepository.ts From gobarber-api with MIT License | 5 votes |
constructor() {
this.ormRepository = getRepository(Appointment);
}
Example #17
Source File: ImportTransactionsService.ts From rocketseat-gostack-11-desafios with MIT License | 5 votes |
async execute({ fileName }: Request): Promise<Transaction[]> {
const parsers = csvParse({ delimiter: ', ', from_line: 2 });
const csvFilePath = path.join(uploadConfig.directory, fileName);
const csvReadStream = fs.createReadStream(csvFilePath);
const parseCSV = csvReadStream.pipe(parsers);
const transactionsRepository = getCustomRepository(TransactionsRepository);
const categoryRepository = getRepository(Category);
const transactionsCSV: TransactionCSV[] = [];
parseCSV.on('data', async line => {
const [title, type, value, category] = line;
transactionsCSV.push({ title, type, value, category });
});
await new Promise(resolve => parseCSV.on('end', resolve));
const categories = transactionsCSV
.map(transection => transection.category)
.filter((elem, pos, self) => {
return self.indexOf(elem) === pos;
})
.map(category => categoryRepository.create({ title: category }));
await getConnection()
.createQueryBuilder()
.insert()
.into(Category)
.values(categories)
.execute();
const transactions = transactionsCSV.map(transaction => {
const category_id = categories.find(
category => category.title === transaction.category,
)?.id;
return transactionsRepository.create({
title: transaction.title,
type: transaction.type,
value: transaction.value,
category_id,
});
});
await getConnection()
.createQueryBuilder()
.insert()
.into(Transaction)
.values(transactions)
.execute();
await fs.promises.unlink(csvFilePath);
return transactions;
}
Example #18
Source File: AppointmentsRepository.ts From hotseat-api with MIT License | 5 votes |
constructor() {
this.ormRepository = getRepository(Appointment);
}
Example #19
Source File: ItemsRepository.ts From ecoleta with MIT License | 5 votes |
constructor() {
this.ormRepository = getRepository(Item);
}
Example #20
Source File: class.routes.ts From Project-template-TS with Apache License 2.0 | 5 votes |
classRouter.get('/', async (request, response) => {
response.json(await getRepository(Class).find());
});
Example #21
Source File: content.routes.ts From Typescript_TypeORM with Apache License 2.0 | 5 votes |
contentRouter.get('/', async (request, response) => {
response.json(await getRepository(Content).find());
});
Example #22
Source File: Comment.resolver.ts From bouncecode-cms with GNU General Public License v3.0 | 5 votes |
@Mutation(() => Number)
async commentDelete(
@Arg('where') where: CommentUniqueWhereInput,
@Ctx() ctx: Context,
) {
try {
const userId = ctx.user.id;
const comment = await getRepository(CommentEntity)
.createQueryBuilder('comment')
.leftJoinAndSelect('comment.user', 'user')
.getOne();
const postId = comment.postId;
if (comment.user.id !== userId) {
throw new ApolloError('권한이 없습니다.');
}
const affected = await getConnection().transaction(
async transactionalEntityManager => {
const queryBuilder = await getConnection()
.createQueryBuilder()
.delete()
.from(CommentEntity)
.where('id = :id', {id: where.id})
.execute();
await transactionalEntityManager
.createQueryBuilder()
.update(CommentStatEntity)
.set({
count: () => 'count - 1',
})
.where('postId = :postId', {postId: postId})
.execute();
return queryBuilder.affected;
},
);
return affected;
} catch (e) {
console.log(e);
return new ApolloError(e);
}
}
Example #23
Source File: CarePlanController.ts From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License | 5 votes |
static listAll = async (req: Request, res: Response) => {
const carePlanRepository = getRepository(OCKCarePlan);
const carePlans = await carePlanRepository.find();
//console.log(util.inspect(carePlans, false, null, true /* enable colors */));
res.send(carePlans);
};