typeorm#FindManyOptions TypeScript Examples
The following examples show how to use
typeorm#FindManyOptions.
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: Pagination.ts From Designer-Server with GNU General Public License v3.0 | 6 votes |
async findBySearchParams(relations, page, perPage, userId?) {
const repo = getRepository(this.type);
if(page) this.page = page;
if(perPage) this.perPage = perPage;
const findOption: FindManyOptions = {
take: this.perPage,
skip: (this.page - 1) * this.perPage
}
if(userId) {
findOption.where = {
userId: userId
}
}
if(relations && relations.length > 0) {
findOption.relations = relations
}
const result = await repo.findAndCount(findOption);
this.items = result[0];
this.totalCount = result[1];
}
Example #3
Source File: polymorphic.repository.ts From typeorm-polymorphic with MIT License | 6 votes |
public async find(
optionsOrConditions?: FindConditions<E> | FindManyOptions<E>,
): Promise<E[]> {
const results = await super.find(optionsOrConditions);
if (!this.isPolymorph()) {
return results;
}
const metadata = this.getPolymorphicMetadata();
return Promise.all(
results.map((entity) => this.hydratePolymorphs(entity, metadata)),
);
}
Example #4
Source File: saved-searches.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
list = wrapHandler(async (event) => {
await connectToDatabase();
const where = { createdBy: { id: event.requestContext.authorizer!.id } };
const pageSize = event.query?.pageSize
? parseInt(event.query.pageSize)
: PAGE_SIZE;
const page = event.query?.page ? parseInt(event.query?.page) : 1;
console.log(event.query);
const result = await SavedSearch.findAndCount({
where,
take: pageSize,
skip: pageSize * (page - 1)
} as FindManyOptions);
return {
statusCode: 200,
body: JSON.stringify({
result: result[0],
count: result[1]
})
};
})
Example #5
Source File: applications.ts From Designer-Server with GNU General Public License v3.0 | 5 votes |
async listApplication(call: grpc.ServerUnaryCall<ListApplicationRequest>, callback: grpc.sendUnaryData<GApplicationList>): Promise<void> {
try {
var page = call.request.getPage();
var perPage = call.request.getPerPage();
var nameSpace = call.request.getNameSpace();
if(!page) page = 1;
if(!perPage) perPage = 10;
const findOption:FindManyOptions = {
select: ["id", "nameSpace", "title", "description" ,"status" ,"userId" ,"createdAt" ,"updatedAt"],
skip: perPage*(page - 1),
take: perPage,
order: {
id: 'ASC'
},
where: {}
}
if (nameSpace) {
findOption.where["nameSpace"] = Like(`%${nameSpace}%`)
}
const applicationRepo = getRepository(Application);
const findResult = await applicationRepo.findAndCount(findOption);
const applicationList = new GApplicationList();
applicationList.setTotalCount(findResult[1]);
applicationList.setPage(page);
applicationList.setPerPage(perPage);
applicationList.setApplicationsList(findResult[0].map((app) => {
const application = new GApplication();
application.setId(app.id);
application.setCreatedAt(app.createdAt.toDateString());
application.setDescription(app.description);
application.setNameSpace(app.nameSpace);
application.setTitle(app.title);
application.setUpdatedAt(app.updatedAt.toDateString());
application.setUserId(app.userId);
return application;
}))
callback(null, applicationList);
} catch (err) {
callback(err, null);
}
}
Example #6
Source File: polymorphic.repository.ts From typeorm-polymorphic with MIT License | 5 votes |
find(options?: FindManyOptions<E>): Promise<E[]>;
Example #7
Source File: index.ts From fosscord-server with GNU Affero General Public License v3.0 | 5 votes |
// https://discord.com/developers/docs/resources/channel#create-message
// get messages
router.get("/", async (req: Request, res: Response) => {
const channel_id = req.params.channel_id;
const channel = await Channel.findOneOrFail({ id: channel_id });
if (!channel) throw new HTTPError("Channel not found", 404);
isTextChannel(channel.type);
const around = req.query.around ? `${req.query.around}` : undefined;
const before = req.query.before ? `${req.query.before}` : undefined;
const after = req.query.after ? `${req.query.after}` : undefined;
const limit = Number(req.query.limit) || 50;
if (limit < 1 || limit > 100) throw new HTTPError("limit must be between 1 and 100", 422);
var halfLimit = Math.floor(limit / 2);
const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
permissions.hasThrow("VIEW_CHANNEL");
if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]);
var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
order: { id: "DESC" },
take: limit,
where: { channel_id },
relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
};
if (after) {
if (after > new Snowflake()) return res.status(422);
query.where.id = MoreThan(after);
}
else if (before) {
if (before < req.params.channel_id) return res.status(422);
query.where.id = LessThan(before);
}
else if (around) {
query.where.id = [
MoreThan((BigInt(around) - BigInt(halfLimit)).toString()),
LessThan((BigInt(around) + BigInt(halfLimit)).toString())
];
}
const messages = await Message.find(query);
const endpoint = Config.get().cdn.endpointPublic;
return res.json(
messages.map((x: any) => {
(x.reactions || []).forEach((x: any) => {
// @ts-ignore
if ((x.user_ids || []).includes(req.user_id)) x.me = true;
// @ts-ignore
delete x.user_ids;
});
// @ts-ignore
if (!x.author) x.author = { id: "4", discriminator: "0000", username: "Fosscord Ghost", public_flags: "0", avatar: null };
x.attachments?.forEach((y: any) => {
// dynamically set attachment proxy_url in case the endpoint changed
const uri = y.proxy_url.startsWith("http") ? y.proxy_url : `https://example.org${y.proxy_url}`;
y.proxy_url = `${endpoint == null ? "" : endpoint}${new URL(uri).pathname}`;
});
/**
Some clients ( discord.js ) only check if a property exists within the response,
which causes erorrs when, say, the `application` property is `null`.
**/
for (var curr in x) {
if (x[curr] === null)
delete x[curr];
}
return x;
})
);
});
Example #8
Source File: purge.ts From fosscord-server with GNU Affero General Public License v3.0 | 5 votes |
/**
TODO: apply the delete bit by bit to prevent client and database stress
**/
router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res: Response) => {
const { channel_id } = req.params;
const channel = await Channel.findOneOrFail({ id: channel_id });
if (!channel.guild_id) throw new HTTPError("Can't purge dm channels", 400);
isTextChannel(channel.type);
const rights = await getRights(req.user_id);
if (!rights.has("MANAGE_MESSAGES")) {
const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
permissions.hasThrow("MANAGE_MESSAGES");
permissions.hasThrow("MANAGE_CHANNELS");
}
const { before, after } = req.body as PurgeSchema;
// TODO: send the deletion event bite-by-bite to prevent client stress
var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
order: { id: "ASC" },
// take: limit,
where: {
channel_id,
id: Between(after, before), // the right way around
author_id: rights.has("SELF_DELETE_MESSAGES") ? undefined : Not(req.user_id)
// if you lack the right of self-deletion, you can't delete your own messages, even in purges
},
relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
};
const messages = await Message.find(query);
const endpoint = Config.get().cdn.endpointPublic;
if (messages.length == 0) {
res.sendStatus(304);
return;
}
await Message.delete(messages.map((x) => ({ id: x })));
await emitEvent({
event: "MESSAGE_DELETE_BULK",
channel_id,
data: { ids: messages.map(x => x.id), channel_id, guild_id: channel.guild_id }
} as MessageDeleteBulkEvent);
res.sendStatus(204);
});