Skip to content

Commit

Permalink
feat: added nestJsTimestampTypeWrapper (#567)
Browse files Browse the repository at this point in the history
* feat: added nestJsTimestampTypeWrapper

* fix: wrappers import

* feat(integration): added nestjs-simple-usedate

* fix: genfiles changes

* revert: protobufjs now fixed on 6.8.8

* update integrations

* improve codegen check for ProtobufTimestampWrapper

* fix lint and rename test

* add additional test

* excluded 2 tests thats failed in CI
  • Loading branch information
PhilipMantrov committed Oct 13, 2022
1 parent 9c2554e commit 59d451e
Show file tree
Hide file tree
Showing 13 changed files with 492 additions and 0 deletions.
17 changes: 17 additions & 0 deletions integration/nestjs-simple-usedate/google/protobuf/empty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */
export const protobufPackage = 'google.protobuf';

/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
* The JSON representation for `Empty` is empty JSON object `{}`.
*/
export interface Empty {}

export const GOOGLE_PROTOBUF_PACKAGE_NAME = 'google.protobuf';
113 changes: 113 additions & 0 deletions integration/nestjs-simple-usedate/google/protobuf/timestamp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/* eslint-disable */
export const protobufPackage = 'google.protobuf';

/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
* ) to obtain a formatter capable of generating timestamps in this format.
*/
export interface Timestamp {
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*/
seconds: number;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*/
nanos: number;
}

export const GOOGLE_PROTOBUF_PACKAGE_NAME = 'google.protobuf';
Binary file added integration/nestjs-simple-usedate/hero.bin
Binary file not shown.
34 changes: 34 additions & 0 deletions integration/nestjs-simple-usedate/hero.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
syntax = "proto3";

import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto";

package hero;

service HeroService {
rpc AddOneHero (Hero) returns (google.protobuf.Empty) {}
rpc FindOneHero (HeroById) returns (Hero) {}
rpc FindOneVillain (VillainById) returns (Villain) {}
rpc FindManyVillain (stream VillainById) returns (stream Villain) {}
rpc FindManyVillainStreamIn (stream VillainById) returns (Villain) {}
rpc FindManyVillainStreamOut (VillainById) returns (stream Villain) {}
}

message HeroById {
int32 id = 1;
}

message VillainById {
int32 id = 1;
}

message Hero {
int32 id = 1;
string name = 2;
google.protobuf.Timestamp birth_date = 3;
}

message Villain {
int32 id = 1;
string name = 2;
}
85 changes: 85 additions & 0 deletions integration/nestjs-simple-usedate/hero.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/* eslint-disable */
import { wrappers } from 'protobufjs';
import { GrpcMethod, GrpcStreamMethod } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { Empty } from './google/protobuf/empty';

export const protobufPackage = 'hero';

export interface HeroById {
id: number;
}

export interface VillainById {
id: number;
}

export interface Hero {
id: number;
name: string;
birthDate: Date | undefined;
}

export interface Villain {
id: number;
name: string;
}

export const HERO_PACKAGE_NAME = 'hero';

wrappers['.google.protobuf.Timestamp'] = {
fromObject(value: Date) {
return {
seconds: value.getTime() / 1000,
nanos: (value.getTime() % 1000) * 1e6,
};
},
toObject(message: { seconds: number; nanos: number }) {
return new Date(message.seconds * 1000 + message.nanos / 1e6);
},
} as any;

export interface HeroServiceClient {
addOneHero(request: Hero): Observable<Empty>;

findOneHero(request: HeroById): Observable<Hero>;

findOneVillain(request: VillainById): Observable<Villain>;

findManyVillain(request: Observable<VillainById>): Observable<Villain>;

findManyVillainStreamIn(request: Observable<VillainById>): Observable<Villain>;

findManyVillainStreamOut(request: VillainById): Observable<Villain>;
}

export interface HeroServiceController {
addOneHero(request: Hero): void;

findOneHero(request: HeroById): Promise<Hero> | Observable<Hero> | Hero;

findOneVillain(request: VillainById): Promise<Villain> | Observable<Villain> | Villain;

findManyVillain(request: Observable<VillainById>): Observable<Villain>;

findManyVillainStreamIn(request: Observable<VillainById>): Promise<Villain> | Observable<Villain> | Villain;

findManyVillainStreamOut(request: VillainById): Observable<Villain>;
}

export function HeroServiceControllerMethods() {
return function (constructor: Function) {
const grpcMethods: string[] = ['addOneHero', 'findOneHero', 'findOneVillain', 'findManyVillainStreamOut'];
for (const method of grpcMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
GrpcMethod('HeroService', method)(constructor.prototype[method], method, descriptor);
}
const grpcStreamMethods: string[] = ['findManyVillain', 'findManyVillainStreamIn'];
for (const method of grpcStreamMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
GrpcStreamMethod('HeroService', method)(constructor.prototype[method], method, descriptor);
}
};
}

export const HERO_SERVICE_NAME = 'HeroService';
26 changes: 26 additions & 0 deletions integration/nestjs-simple-usedate/nestjs-project/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { HERO_PACKAGE_NAME } from '../hero';
import { HeroController } from './hero.controller';

@Module({
imports: [
ClientsModule.register([
{
name: HERO_PACKAGE_NAME,
transport: Transport.GRPC,
options: {
url: '0.0.0.0:8080',
package: HERO_PACKAGE_NAME,
protoPath: join(__dirname, '../hero.proto'),
loader: {
longs: Number,
},
},
},
]),
],
controllers: [HeroController],
})
export class AppModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Controller } from '@nestjs/common';
import { Observable, Subject } from 'rxjs';
import { Hero, HeroById, HeroServiceController, HeroServiceControllerMethods, Villain, VillainById } from '../hero';

@Controller('hero')
@HeroServiceControllerMethods()
export class HeroController implements HeroServiceController {
private readonly heroes: Hero[] = [
{ id: 1, name: 'Stephenh', birthDate: new Date("2000/01/01") },
{ id: 2, name: 'Iangregsondev', birthDate: new Date("2000/02/02") },
];

private readonly villains: Villain[] = [{ id: 1, name: 'John' }, { id: 2, name: 'Doe' }];

addOneHero(request: Hero) {
this.heroes.push(request);
}

async findOneHero(data: HeroById): Promise<Hero> {
return this.heroes.find(({ id }) => id === data.id)!;
}

async findOneVillain(data: VillainById): Promise<Villain> {
return this.villains.find(({ id }) => id === data.id)!;
}

findManyVillain(request: Observable<VillainById>): Observable<Villain> {
const hero$ = new Subject<Villain>();

const onNext = (villainById: VillainById) => {
const item = this.villains.find(({ id }) => id === villainById.id);
hero$.next(item!);
};
const onComplete = () => hero$.complete();
request.subscribe(onNext, null, onComplete);

return hero$.asObservable();
}

findManyVillainStreamIn(request: Observable<VillainById>): Observable<Villain> {
return null!;
}

findManyVillainStreamOut(request: VillainById): Observable<Villain> {
return null!;
}
}
21 changes: 21 additions & 0 deletions integration/nestjs-simple-usedate/nestjs-project/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { HERO_PACKAGE_NAME } from '../hero';
import { AppModule } from './app.module';

export async function createApp() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
transport: Transport.GRPC,
options: {
url: '0.0.0.0:8080',
package: HERO_PACKAGE_NAME,
protoPath: join(__dirname, '../hero.proto'),
loader: {
longs: Number,
},
},
});

return app;
}
Loading

0 comments on commit 59d451e

Please sign in to comment.