Skip to content

Commit

Permalink
Merge pull request #568 from lens-protocol/fix/simplify-parametrized-…
Browse files Browse the repository at this point in the history
…edges

fix: simplifies parametrized edges
  • Loading branch information
cesarenaldi authored Oct 6, 2023
2 parents 37d0338 + b228149 commit 4a4bb11
Show file tree
Hide file tree
Showing 55 changed files with 1,297 additions and 1,111 deletions.
2 changes: 1 addition & 1 deletion packages/api-bindings/codegen-api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ generates:
"import type { EvmAddress, Url } from '@lens-protocol/shared-kernel';",
"import type { ContentEncryptionKey } from '../ContentEncryptionKey';",
"import type { Cursor } from '../Cursor';",
"import type { ImageSizeTransform } from '../ImageSizeTransform';",
"import type { ImageSizeTransform } from '../ImageTransform';",
]
- 'typescript-operations':
skipTypename: true
Expand Down
3 changes: 2 additions & 1 deletion packages/api-bindings/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@
},
"license": "MIT",
"dependencies": {
"@apollo/client": "^3.7.1",
"@lens-protocol/domain": "workspace:*",
"@lens-protocol/shared-kernel": "workspace:*",
"graphql": "^16.6.0",
"graphql-tag": "^2.12.6",
"tslib": "^2.5.0"
},
"devDependencies": {
"@apollo/client": "^3.8.5",
"@babel/core": "^7.20.12",
"@babel/preset-env": "^7.20.2",
"@babel/preset-typescript": "^7.18.6",
Expand Down Expand Up @@ -74,6 +74,7 @@
"typescript": "^4.9.5"
},
"peerDependencies": {
"@apollo/client": "^3.8.5",
"@faker-js/faker": "^7.6.0",
"react": "^18.2.0"
},
Expand Down
10 changes: 7 additions & 3 deletions packages/api-bindings/src/apollo/IGraphQLClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,19 @@ export function assertGraphQLClientMutationResult<TData>(
}

export interface IGraphQLClient<TCacheShape extends NormalizedCacheObject> {
query<TData = unknown, TVariables = OperationVariables>(
query<TData = unknown, TVariables extends OperationVariables = OperationVariables>(
options: QueryOptions<TVariables, TData>,
): Promise<GraphQLClientQueryResult<TData>>;

mutate<TData = unknown, TVariables = OperationVariables, TContext = DefaultContext>(
mutate<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
TContext extends DefaultContext = DefaultContext,
>(
options: MutationOptions<TData, TVariables, TContext, ApolloCache<TCacheShape>>,
): Promise<GraphQLClientMutationResult<TData>>;

poll<TData = unknown, TVariables = OperationVariables>(
poll<TData = unknown, TVariables extends OperationVariables = OperationVariables>(
options: QueryOptions<TVariables, TData>,
): Observable<TData>;
}
10 changes: 7 additions & 3 deletions packages/api-bindings/src/apollo/SafeApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class SafeApolloClient<TCacheShape extends NormalizedCacheObject = Normal
this.pollingInterval = pollingInterval;
}

async query<TData = unknown, TVariables = OperationVariables>(
async query<TData = unknown, TVariables extends OperationVariables = OperationVariables>(
options: QueryOptions<TVariables, TData>,
): Promise<GraphQLClientQueryResult<TData>> {
try {
Expand All @@ -103,7 +103,11 @@ export class SafeApolloClient<TCacheShape extends NormalizedCacheObject = Normal
}
}

async mutate<TData = unknown, TVariables = OperationVariables, TContext = DefaultContext>(
async mutate<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
TContext extends DefaultContext = DefaultContext,
>(
options: MutationOptions<TData, TVariables, TContext, ApolloCache<TCacheShape>>,
): Promise<GraphQLClientMutationResult<TData>> {
try {
Expand All @@ -117,7 +121,7 @@ export class SafeApolloClient<TCacheShape extends NormalizedCacheObject = Normal
}
}

poll<TData = unknown, TVariables = OperationVariables>(
poll<TData = unknown, TVariables extends OperationVariables = OperationVariables>(
options: QueryOptions<TVariables, TData>,
): Observable<TData> {
const observable = super.watchQuery<TData, TVariables>(options);
Expand Down
9 changes: 7 additions & 2 deletions packages/api-bindings/src/apollo/cache/createLensCache.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { ApolloCache, InMemoryCache, NormalizedCacheObject } from '@apollo/client';

import generatedIntrospection from '../../lens/graphql/generated';
import { QueryParams } from './createQueryParamsLocalFields';
import { createTypePolicies } from './createTypePolicies';

export function createLensCache(): ApolloCache<NormalizedCacheObject> {
export type { QueryParams };

export { defaultQueryParams } from './createQueryParamsLocalFields';

export function createLensCache(options?: QueryParams): ApolloCache<NormalizedCacheObject> {
return new InMemoryCache({
possibleTypes: generatedIntrospection.possibleTypes,
typePolicies: createTypePolicies(),
typePolicies: createTypePolicies(options),
});
}
103 changes: 103 additions & 0 deletions packages/api-bindings/src/apollo/cache/createQueryParamsLocalFields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { FieldReadFunction } from '@apollo/client';

import { ImageSizeTransform, ImageTransform, SupportedFiatType } from '../../lens';

/**
* The common query parameters used across any query.
*/
export type QueryParams = {
image: {
/**
* The size of the small publication image
*/
small: ImageTransform;
/**
* The size of the medium publication image
*/
medium: ImageTransform;
};
profile: {
/**
* The size of optimized profile image
*/
thumbnail: ImageTransform;
/**
* The size of the cover image
*/
cover: ImageTransform;
};
/**
* The fiat currency to use for the fx rate
*/
fxRateFor: SupportedFiatType;
};

function buildImageTransform(
width: ImageSizeTransform,
height: ImageSizeTransform = 'auto',
): ImageTransform {
return {
width,
height,
keepAspectRatio: true,
};
}

/**
* The default query parameters.
*/
export const defaultQueryParams: QueryParams = {
image: {
small: buildImageTransform('400px'),
medium: buildImageTransform('700px'),
},
profile: {
thumbnail: buildImageTransform('256px'),
cover: buildImageTransform('1100px'),
},
fxRateFor: SupportedFiatType.Usd,
};

/**
* @internal
*/
export type LocalOnlyFieldPolicies = {
fxRateFor: FieldReadFunction<SupportedFiatType>;

profileCoverSize: FieldReadFunction<ImageTransform>;

profilePictureSize: FieldReadFunction<ImageTransform>;

imageSmallSize: FieldReadFunction<ImageTransform>;

imageMediumSize: FieldReadFunction<ImageTransform>;
};

/**
* @internal
*/
export function createQueryParamsLocalFields(
params: QueryParams = defaultQueryParams,
): LocalOnlyFieldPolicies {
return {
fxRateFor() {
return params.fxRateFor;
},

profileCoverSize() {
return params.profile.cover;
},

profilePictureSize() {
return params.profile.thumbnail;
},

imageSmallSize() {
return params.image.small;
},

imageMediumSize() {
return params.image.medium;
},
};
}
7 changes: 6 additions & 1 deletion packages/api-bindings/src/apollo/cache/createTypePolicies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createMutualFollowersFieldPolicy } from './createMutualFollowersFieldPo
import { createProfilesFieldPolicy } from './createProfilesFieldPolicy';
import { createPublicationTypePolicy } from './createPublicationTypePolicy';
import { createPublicationsFieldPolicy } from './createPublicationsFieldPolicy';
import { createQueryParamsLocalFields, QueryParams } from './createQueryParamsLocalFields';
import { createSearchProfilesFieldPolicy } from './createSearchProfilesFieldPolicy';
import { createSearchPublicationsFieldPolicy } from './createSearchPublicationsFieldPolicy';
import { notNormalizedType } from './utils/notNormalizedType';
Expand All @@ -16,7 +17,9 @@ type InheritedTypePolicies = {
Publication: TypePolicy;
};

export function createTypePolicies(): StrictTypedTypePolicies & InheritedTypePolicies {
export function createTypePolicies(
params?: QueryParams,
): StrictTypedTypePolicies & InheritedTypePolicies {
return {
Publication: createPublicationTypePolicy(),
Post: notNormalizedType(),
Expand All @@ -37,6 +40,8 @@ export function createTypePolicies(): StrictTypedTypePolicies & InheritedTypePol
searchPublications: createSearchPublicationsFieldPolicy(),
searchProfiles: createSearchProfilesFieldPolicy(),
feed: createFeedFieldPolicy(),

...createQueryParamsLocalFields(params),
},
},
};
Expand Down
8 changes: 6 additions & 2 deletions packages/api-bindings/src/apollo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { LENS_API_MINIMAL_SUPPORTED_VERSION } from '../constants';
import type { IAccessTokenStorage } from './IAccessTokenStorage';
import { SafeApolloClient } from './SafeApolloClient';
import { createSnapshotCache } from './cache';
import { createLensCache } from './cache/createLensCache';
import { createLensCache, QueryParams } from './cache/createLensCache';
import { ContentInsightMatcher } from './cache/utils/ContentInsight';
import { createAuthLink, createLensLink, createSnapshotLink } from './links';

Expand All @@ -18,13 +18,15 @@ export type ApolloClientConfig = {
logger: ILogger;
pollingInterval: number;
contentMatchers: ContentInsightMatcher[];
queryParams: QueryParams;
};

export function createLensApolloClient({
accessTokenStorage,
backendURL,
logger,
pollingInterval,
queryParams,
}: ApolloClientConfig) {
const uri = `${backendURL}/graphql`;

Expand All @@ -38,7 +40,7 @@ export function createLensApolloClient({

return new SafeApolloClient({
connectToDevTools: true,
cache: createLensCache(),
cache: createLensCache(queryParams),
link: from([authLink, httpLink]),
pollingInterval,
version: LENS_API_MINIMAL_SUPPORTED_VERSION,
Expand Down Expand Up @@ -74,6 +76,8 @@ export function createSnapshotApolloClient({ backendURL }: SnapshotApolloClientC
}

export type { IAccessTokenStorage };
export { defaultQueryParams } from './cache/createLensCache';
export type { QueryParams };
export type { IGraphQLClient } from './IGraphQLClient';
export * from './errors';
export * from './cache/transactions';
Expand Down
7 changes: 5 additions & 2 deletions packages/api-bindings/src/apollo/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,21 @@ export function createAuthLink(accessTokenStorage: IAccessTokenStorage) {
return;
});

const authHeaderLink = setContext(() => {
const authHeaderLink = setContext((_, prevContext) => {
const token = accessTokenStorage.getAccessToken();

if (token) {
return {
...prevContext,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
headers: {
authorization: `Bearer ${token}`,
...('headers' in prevContext && prevContext.headers),
},
};
}

return;
return prevContext;
});

return from([errorLink, authHeaderLink]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type Pixel =

export type ImageSizeTransform = Pixel | Percentage | 'auto';

export type MediaTransformParams = {
export type ImageTransform = {
/**
* Set the transformed image's width. You can use specific size in
* pixels eg. 100px, a percentage eg. 50% or set as 'auto' to be set automatically.
Expand Down
25 changes: 13 additions & 12 deletions packages/api-bindings/src/lens/__helpers__/fragments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,19 +152,20 @@ export function mockPublicationTextOnlyMetadata(overrides: Partial<TextOnlyMetad
};
}

export function mockPublicationOperationsFragment(overrides: Partial<PublicationOperations> = {}) {
export function mockPublicationOperationsFragment(
overrides: Partial<PublicationOperations> = {},
): PublicationOperations {
return {
isNotInterested: false,
hasBookmarked: false,
hasReported: false,
canAct: TriStateValue.Unknown,
canCollect: TriStateValue.Unknown,
canComment: TriStateValue.Unknown,
canMirror: TriStateValue.Unknown,
hasMirrored: false,
hasUpvoted: false,
hasDownvoted: false,
hasActed: { value: false, isFinalisedOnchain: false },
actedOn: [],
hasCollected: { value: false, isFinalisedOnchain: false },
canDecrypt: {
result: false,
reasons: null,
Expand Down Expand Up @@ -196,9 +197,9 @@ export function mockPublicationStatsFragment(
mirrors: faker.datatype.number(),
quotes: faker.datatype.number(),
bookmarks: faker.datatype.number(),
countOpenActions: faker.datatype.number(),
upvoteReactions: faker.datatype.number(),
downvoteReactions: faker.datatype.number(),
collects: faker.datatype.number(),
upvotes: faker.datatype.number(),
downvotes: faker.datatype.number(),

...overrides,
};
Expand All @@ -214,11 +215,11 @@ export function mockProfileStatsFragment(overrides: Partial<ProfileStats> = {}):
mirrors: faker.datatype.number(),
quotes: faker.datatype.number(),
publications: faker.datatype.number(),
countOpenActions: faker.datatype.number(),
upvoteReactions: faker.datatype.number(),
downvoteReactions: faker.datatype.number(),
upvoteReacted: faker.datatype.number(),
downvoteReacted: faker.datatype.number(),
collects: faker.datatype.number(),
upvotes: faker.datatype.number(),
downvotes: faker.datatype.number(),
upvoted: faker.datatype.number(),
downvoted: faker.datatype.number(),

...overrides,
};
Expand Down
Loading

0 comments on commit 4a4bb11

Please sign in to comment.