-
Notifications
You must be signed in to change notification settings - Fork 1
/
repository.ts
67 lines (48 loc) · 2.28 KB
/
repository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { List, Model } from '@chubbyts/chubbyts-api/dist/model';
import type { FindOneById, Persist, Remove, ResolveList } from '@chubbyts/chubbyts-api/dist/repository';
import type { Filter, MongoClient, WithId } from 'mongodb';
const withoutMongoId = <C>(model: WithId<Model<C>>): Model<C> => {
const { _id, ...rest } = model;
return rest as Model<C>;
};
export const createResolveList = <C>(mongoClient: MongoClient, collectionName: string): ResolveList<Model<C>> => {
const collection = mongoClient.db().collection<Model<C>>(collectionName);
return async (list: List<Model<C>>): Promise<List<Model<C>>> => {
const cursor = collection.find(list.filters as Filter<Model<C>>);
cursor.skip(list.offset);
cursor.limit(list.limit);
// eslint-disable-next-line functional/immutable-data
cursor.sort(list.sort);
return {
...list,
items: (await cursor.toArray()).map(withoutMongoId),
count: await collection.countDocuments(list.filters as Filter<Model<C>>),
};
};
};
export const createFindOneById = <C>(mongoClient: MongoClient, collectionName: string): FindOneById<Model<C>> => {
const collection = mongoClient.db().collection<Model<C>>(collectionName);
return async (id: string): Promise<Model<C> | undefined> => {
const modelWithMongoId = await collection.findOne({ id } as Filter<Model<C>>);
if (!modelWithMongoId) {
return undefined;
}
return withoutMongoId(modelWithMongoId);
};
};
export const createPersist = <C>(mongoClient: MongoClient, collectionName: string): Persist<Model<C>> => {
const collection = mongoClient.db().collection<Model<C>>(collectionName);
return async (model: Model<C>): Promise<Model<C>> => {
const filter = { id: model.id } as Filter<Model<C>>;
await collection.replaceOne(filter, model, { upsert: true });
const modelWithMongoId = (await collection.findOne(filter)) as WithId<Model<C>>;
return withoutMongoId(modelWithMongoId);
};
};
export const createRemove = <C>(mongoClient: MongoClient, collectionName: string): Remove<Model<C>> => {
const collection = mongoClient.db().collection<Model<C>>(collectionName);
return async (model: Model<C>): Promise<void> => {
const filter = { id: model.id } as Filter<Model<C>>;
await collection.deleteOne(filter);
};
};