Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: persist shares and return aggregated purchase history #30

Merged
merged 2 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/src/shares/shares.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class SharesController {
@ApiBody({
type: BuySharesDto,
})
send(@Body() req: BuySharesDto) {
buyShares(@Body() req: BuySharesDto) {
return this.sharesService.buyShares(req);
}
}
1 change: 1 addition & 0 deletions apps/shares/.env.manual
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
NODE_ENV='development'
SHARES_GRPC_URL='0.0.0.0:4070'
DATABASE_URL=mongodb://bs:password@mongodb:27017
2 changes: 2 additions & 0 deletions apps/shares/src/db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './shares.repository';
export * from './shares.schema';
17 changes: 17 additions & 0 deletions apps/shares/src/db/shares.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Injectable, Logger } from '@nestjs/common';
import { AbstractRepository } from '@bitsacco/common';
import { SharesDocument } from './shares.schema';

@Injectable()
export class SharesRepository extends AbstractRepository<SharesDocument> {
protected readonly logger = new Logger(SharesRepository.name);

constructor(
@InjectModel(SharesDocument.name)
reservationModel: Model<SharesDocument>,
) {
super(reservationModel);
}
}
13 changes: 13 additions & 0 deletions apps/shares/src/db/shares.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { AbstractDocument } from '@bitsacco/common';

@Schema({ versionKey: false })
export class SharesDocument extends AbstractDocument {
@Prop({ type: String, required: true })
userId: string;

@Prop({ type: Number, required: true })
quantity: number;
}

export const SharesSchema = SchemaFactory.createForClass(SharesDocument);
10 changes: 8 additions & 2 deletions apps/shares/src/shares.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as Joi from 'joi';
import { Module } from '@nestjs/common';
import { LoggerModule } from '@bitsacco/common';
import { DatabaseModule, LoggerModule } from '@bitsacco/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SharesController } from './shares.controller';
import { SharesService } from './shares.service';
import { SharesDocument, SharesRepository, SharesSchema } from './db';

@Module({
imports: [
Expand All @@ -12,11 +13,16 @@ import { SharesService } from './shares.service';
validationSchema: Joi.object({
NODE_ENV: Joi.string().required(),
SHARES_GRPC_URL: Joi.string().required(),
DATABASE_URL: Joi.string().required(),
}),
}),
DatabaseModule,
DatabaseModule.forFeature([
{ name: SharesDocument.name, schema: SharesSchema },
]),
LoggerModule,
],
controllers: [SharesController],
providers: [SharesService, ConfigService],
providers: [SharesService, ConfigService, SharesRepository],
})
export class SharesModule {}
35 changes: 32 additions & 3 deletions apps/shares/src/shares.service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,44 @@
import { Injectable, Logger } from '@nestjs/common';
import { BuySharesDto } from '@bitsacco/common';
import { BuySharesDto, ShareDetailResponse } from '@bitsacco/common';
import { SharesRepository } from './db';

@Injectable()
export class SharesService {
private readonly logger = new Logger(SharesService.name);

constructor() {
constructor(private readonly shares: SharesRepository) {
this.logger.log('SharesService created');
}

async buyShares({ userId, quantity }: BuySharesDto): Promise<void> {
async buyShares({
userId,
quantity,
}: BuySharesDto): Promise<ShareDetailResponse> {
this.logger.debug(`Buying ${quantity} Bitsacco shares for ${userId}`);

await this.shares.create({
userId,
quantity,
});

const allShares = await this.shares.find({ userId });
const totalShares = allShares.reduce(
(sum, share) => sum + share.quantity,
0,
);
const shares = allShares
.map((share) => ({
quantity: share.quantity,
purchasedAtUnix: Number(share.createdAt),
}))
.reverse();

const res: ShareDetailResponse = {
userId,
totalShares,
shares,
};

return Promise.resolve(res);
}
}
1 change: 0 additions & 1 deletion libs/common/src/database/abstract.schema.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { v4 as uuidv4 } from 'uuid';
import { SchemaTypes } from 'mongoose';
import { Prop, Schema } from '@nestjs/mongoose';
import { UUID } from 'crypto';

@Schema()
export class AbstractDocument {
Expand Down
23 changes: 15 additions & 8 deletions libs/common/src/types/proto/shares.ts

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

17 changes: 12 additions & 5 deletions proto/shares.proto
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,23 @@ import "lib.proto";
package shares;

service SharesService {
rpc BuyShares(BuySharesRequest) returns (BuySharesResponse);
rpc BuyShares(BuySharesRequest) returns (ShareDetailResponse);
}

message BuySharesRequest {
string user_id = 1;
int32 quantity = 3;
}

message BuySharesResponse {
bool success = 1;
string message = 2;
double total_cost = 3;
message ShareDetailResponse {
string user_id = 1;
int32 total_shares = 2;
repeated ShareDetails shares = 3;
}

message ShareDetails {
// Number of shared purchased
int32 quantity = 1;
// Unix timestamp for when the shares were purchased
int64 purchasedAtUnix = 3;
}
Loading