Skip to content

Commit

Permalink
refactor: migrate from npm mongo client to jsr
Browse files Browse the repository at this point in the history
  • Loading branch information
wax911 committed Nov 21, 2024
1 parent 24e48fd commit f758015
Show file tree
Hide file tree
Showing 17 changed files with 73 additions and 64 deletions.
27 changes: 24 additions & 3 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/common/mongo/collection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Document } from 'npm/mongodb';
import { Document } from 'mongo';
import { Local } from '../types/core.ts';

export const collection = <T extends Document>(
Expand Down
41 changes: 16 additions & 25 deletions src/common/mongo/factory.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,43 @@
import { MongoClient } from 'npm/mongodb';
import { MongoClient } from 'mongo';
import { logger } from '../core/logger.ts';
import { between } from 'optic';
import { env } from '../core/env.ts';
import { Local } from '../types/core.ts';

class LocalSourceFactory {
constructor(private readonly client: MongoClient) {
logger.mark('mongo_connection_start');
client.on('timeout', () => {
logger.warn(
'common.mongo.factory:LocalSourceFactory: Connection timed out',
);
});
}
constructor(private readonly client: MongoClient) {}

connect = async (): Promise<Local> => {
return await this.client.connect()
logger.mark('mongo_connection_start');
return await this.client.connect(env<string>('MONGO_URL'))
.then((client) => {
logger.mark('mongo_connection_end');
logger.measure(
between('mongo_connection_start', 'mongo_connection_end'),
);
return client.db();
return client;
})
.catch((e) => {
.catch((e: unknown) => {
logger.error('common.mongo.factory:connect:', e);
return undefined;
});
};

disconnect = async () => {
disconnect = () => {
logger.mark('mongo_close_start');
await this.client.close(true)
.then(() => {
}).catch((e) => {
logger.error('common.mongo.factory:disconnect:', e);
}).finally(() => {
logger.mark('mongo_close_end');
logger.measure(between('mongo_close_start', 'mongo_close_end'));
});
try {
this.client.close();
} catch (e) {
logger.error('common.mongo.factory:disconnect:', e);
} finally {
logger.mark('mongo_close_end');
logger.measure(between('mongo_close_start', 'mongo_close_end'));
}
};
}

const _localSourceFactory = new LocalSourceFactory(
new MongoClient(env<string>('MONGO_URL'), {
connectTimeoutMS: 1000,
monitorCommands: true,
}),
new MongoClient(),
);

export default _localSourceFactory;
6 changes: 3 additions & 3 deletions src/common/mongo/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Document, OptionalId, SortDirection } from 'npm/mongodb';
import { Document } from 'mongo';

export type Optional<T extends Document> = T | undefined | null;

export type ProjectionOption<T extends Document> = {
[K in keyof OptionalId<T>]?: 0 | 1;
[K in keyof T]?: 0 | 1;
};

export type SortOption<T extends Document> = {
[K in keyof OptionalId<T>]?: SortDirection;
[K in keyof T]?: 1 | -1 | 'asc' | 'desc';
};

export interface EntityCursor {
Expand Down
5 changes: 2 additions & 3 deletions src/common/mongo/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Document, ObjectId, Sort } from 'npm/mongodb';
import { Document, ObjectId } from 'mongo';
import { ProjectionOption, SortOption } from './types.ts';

export const projectionOf = <T extends Document>(
projection: ProjectionOption<T>,
) => projection;

export const sortOf = <T extends Document>(option: SortOption<T>): Sort =>
option as Sort;
export const sortOf = <T extends Document>(option: SortOption<T>) => option;

export const idOf = (id: ObjectId): string => id.toHexString();
4 changes: 2 additions & 2 deletions src/common/types/core.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Context } from 'oak';
import { State } from './state.ts';
import { GrowthBook } from 'growthbook';
import { Db } from 'npm/mongodb';
import { Database } from 'mongo';
import { AppFeatures } from '../experiment/types.ts';

export type RCF822Date = string;
Expand All @@ -14,4 +14,4 @@ export type AppContext = Context<State>;

export type Features = GrowthBook<AppFeatures>;

export type Local = Db | undefined;
export type Local = Database | undefined;
4 changes: 2 additions & 2 deletions src/config/local/source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Collection, WithId } from 'npm/mongodb';
import { Collection } from 'mongo';
import { logger } from '../../common/core/logger.ts';
import { ConfigDocument } from './types.ts';
import { Optional } from '../../common/mongo/types.ts';
Expand All @@ -8,7 +8,7 @@ export class LocalSource {
private readonly collection?: Collection<ConfigDocument>,
) {}

getConfig = async (): Promise<Optional<WithId<ConfigDocument>>> => {
getConfig = async (): Promise<Optional<ConfigDocument>> => {
const config = await this.collection?.findOne()
?.catch((e) => {
logger.error(
Expand Down
2 changes: 1 addition & 1 deletion src/config/local/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Document } from 'npm/mongodb';
import { Document } from 'mongo';

export interface NavigationConfig extends Document {
criteria: string;
Expand Down
3 changes: 1 addition & 2 deletions src/config/transformer/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { WithId } from 'npm/mongodb';
import {
getPlatformSource,
isAnalyticsEnabled,
Expand All @@ -19,7 +18,7 @@ const toImageUrl = (image: string, source?: PlatformSource): string => {

export const transform: Transform<
{
document: WithId<ConfigDocument>;
document: ConfigDocument;
features: Features;
},
ClientConfiguration
Expand Down
4 changes: 2 additions & 2 deletions src/import_map.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"deepmerge": "jsr:@rebeccastevens/[email protected]",
"growthbook": "jsr:@growthbook/[email protected]",
"xml": "jsr:@libs/[email protected]",
"npm/logtail": "npm:@logtail/node@0.5.2",
"npm/mongodb": "npm:[email protected]"
"mongo": "jsr:@db/mongo@0.33.0",
"npm/logtail": "npm:@logtail/[email protected]"
}
}
6 changes: 3 additions & 3 deletions src/news/local/source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Collection, Filter, FindOptions, ObjectId, WithId } from 'npm/mongodb';
import { Collection, Filter, FindOptions, ObjectId } from 'mongo';
import { logger } from '../../common/core/logger.ts';
import { IPaging } from '../../common/types/paging.ts';
import { IResponse } from '../../common/types/response.ts';
Expand Down Expand Up @@ -42,7 +42,7 @@ export default class LocalSource {
const filter: Filter<NewsDocument> = {
id: { $exists: true },
};
const options: FindOptions<WithId<NewsDocument>> = {
const options: FindOptions = {
projection: projectionOf<NewsDocument>({ published_on: 1 }),
sort: sortOf<NewsDocument>({ published_on: 'desc' }),
};
Expand Down Expand Up @@ -76,7 +76,7 @@ export default class LocalSource {
_id: { $gt: new ObjectId(id.cursor) },
}
: {};
const options: FindOptions<WithId<NewsDocument>> = {
const options: FindOptions = {
sort: sortOf<NewsDocument>({ published_on: 'desc' }),
limit: 25,
};
Expand Down
2 changes: 1 addition & 1 deletion src/news/local/transformer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Document } from 'npm/mongodb';
import { Document } from 'mongo';
import { Transform } from '../../common/transformer/types.ts';
import { News } from '../types.ts';

Expand Down
2 changes: 1 addition & 1 deletion src/news/local/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Document } from 'npm/mongodb';
import { Document } from 'mongo';
import { EntityCursor } from '../../common/mongo/types.ts';

export interface NewsDocument extends Document {
Expand Down
5 changes: 2 additions & 3 deletions src/news/mapper.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { News, NewsEntity } from './types.ts';
import { NewsDocument } from './local/types.ts';
import { OptionalId, WithId } from 'npm/mongodb';
import { idOf } from '../common/mongo/index.ts';

export const toEntity = (data: WithId<NewsDocument>): NewsEntity => {
export const toEntity = (data: NewsDocument): NewsEntity => {
return {
id: idOf(data._id),
slug: data.slug,
Expand All @@ -18,7 +17,7 @@ export const toEntity = (data: WithId<NewsDocument>): NewsEntity => {
};
};

export const toDocument = (data: News): OptionalId<NewsDocument> => {
export const toDocument = (data: News): NewsDocument => {
return {
slug: data.slug,
title: data.title,
Expand Down
17 changes: 9 additions & 8 deletions src/series/local/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import {
Collection,
Document,
Filter,
FindOneAndReplaceOptions,
} from 'npm/mongodb';
FindAndModifyOptions,
FindOptions,
} from 'mongo';
import { logger } from '../../common/core/logger.ts';
import { IResponse } from '../../common/types/response.ts';
import { MediaWithSeason } from '../types.ts';
import { transform } from './transformer.ts';
import { MediaDocument } from './types.ts';
import { MediaParamId } from './types.ts';
import { FindOptions } from 'npm/mongodb';
import { between } from 'optic';

export default class LocalSource {
Expand All @@ -22,7 +22,7 @@ export default class LocalSource {
const filter: Filter<Document> = {
'mediaId.anilist': mediaId.anilist,
};
const options: FindOptions<MediaDocument> = {};
const options: FindOptions = {};
logger.mark('series_source_get_start');
const document = await this.collection
?.findOne(filter, options)
Expand Down Expand Up @@ -56,15 +56,16 @@ export default class LocalSource {
const filter: Filter<Document> = {
'mediaId.anilist': media.mediaId.anilist,
};
const options: FindOneAndReplaceOptions = {
upsert: true,
};
const replacement: MediaDocument = {
...media,
};
const options: FindAndModifyOptions = {
upsert: true,
update: replacement,
};

logger.mark('series_source_save_start');
await this.collection?.findOneAndReplace(filter, replacement, options)
await this.collection?.findAndModify(filter, options)
?.then((result) => {
logger.debug('seriese.local.source:save: Saved document', result?._id);
logger.mark('series_source_save_end');
Expand Down
5 changes: 2 additions & 3 deletions src/series/local/transformer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { WithId } from 'npm/mongodb';
import { Transform } from '../../common/transformer/types.ts';
import { MediaEntity } from '../types.ts';
import { idOf, Optional } from '../../common/mongo/index.ts';
import { MediaDocument } from './types.ts';

const map = (
document: WithId<MediaDocument>,
document: MediaDocument,
): Optional<MediaEntity> => {
return {
id: idOf(document._id),
Expand Down Expand Up @@ -33,6 +32,6 @@ const map = (
};

export const transform: Transform<
Optional<WithId<MediaDocument>>,
Optional<MediaDocument>,
Optional<MediaEntity>
> = (sourceData) => sourceData ? map(sourceData) : undefined;
2 changes: 1 addition & 1 deletion src/series/local/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Document } from 'npm/mongodb';
import { Document } from 'mongo';
import { MediaWithSeason } from '../types.ts';

export interface MediaDocument extends Document, MediaWithSeason {
Expand Down

0 comments on commit f758015

Please sign in to comment.