Skip to content

Commit

Permalink
Merge pull request #52 from vuestorefront-community/dev
Browse files Browse the repository at this point in the history
chore: release version 1.5.0
  • Loading branch information
odranoelBR authored Mar 2, 2023
2 parents cc0406d + fa0866e commit 8a1a094
Show file tree
Hide file tree
Showing 27 changed files with 2,577 additions and 209 deletions.
9 changes: 6 additions & 3 deletions packages/api-client/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@vue-storefront/odoo-api",
"version": "1.4.1",
"version": "1.4.3-rc.18",
"private": false,
"sideEffects": false,
"server": "server/index.js",
Expand All @@ -17,15 +17,18 @@
"update:update": "ncu -u"
},
"dependencies": {
"@vue-storefront/core": "2.5.6",
"@vue-storefront/core": "2.7.5",
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link": "^1.2.14",
"apollo-link-error": "^1.1.13",
"apollo-link-http": "^1.5.17",
"graphql": "^15.5.0",
"graphql-tag": "^2.12.4",
"isomorphic-fetch": "^3.0.0"
"ioredis": "^5.2.4",
"isomorphic-fetch": "^3.0.0",
"redis-tag-cache": "^1.2.1",
"request-ip": "^3.3.0"
},
"devDependencies": {
"@rollup/plugin-graphql": "^1.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import gql from 'graphql-tag';
export default gql`
mutation($promo: String!){
applyCoupon(promo: $promo){
applied
error
}
}`;
19 changes: 18 additions & 1 deletion packages/api-client/src/api/getCategory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,22 @@ import ApolloClient from 'apollo-client';
import query from './getCategoryQuery';
import { CategoryResult, GraphQlGetCategoryParams } from '../../index';
import { FetchResult } from 'apollo-link';
import { randomIntegerBetween } from '../../';

export default async function getCategory(
context: Context,
params: GraphQlGetCategoryParams,
customQuery?: CustomQuery
customQuery?: CustomQuery,
cacheKey?: string
): Promise<FetchResult<CategoryResult>> {
const redisClient = context.client.redisTagClient;
const apolloClient = context.client.apollo as ApolloClient<any>;

let cachedCategory = null;
if (cacheKey && redisClient && (cachedCategory = await redisClient.get(cacheKey))) {
return cachedCategory;
}

const { getCategory } = context.extendQuery(
customQuery, { getCategory: { query, variables: params } }
);
Expand All @@ -24,5 +32,14 @@ export default async function getCategory(
fetchPolicy: 'no-cache'
});

delete response?.data?.cookie;
if (cacheKey && redisClient && response.data?.category) {
redisClient.set(
cacheKey,
response,
[`API-C${response.data.category.id}`],
{ timeout: process.env.REDIS_TTL_CACHE_MAXIMUM ? randomIntegerBetween(Number(process.env.REDIS_TTL_CACHE_MINIMUM), Number(process.env.REDIS_TTL_CACHE_MAXIMUM)) : 86400 });
}

return response;
}
21 changes: 20 additions & 1 deletion packages/api-client/src/api/getProductTemplate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@ import ApolloClient from 'apollo-client';
import query from './getProductTemplateQuery';
import { GraphQlGetProductTemplateParams, SingleProductResult } from '../../index';
import { FetchResult } from 'apollo-link/lib/types';
import { randomIntegerBetween } from '../../';

export default async function getProductTemplate(
context: Context,
params: GraphQlGetProductTemplateParams,
customQuery?: CustomQuery
customQuery?: CustomQuery,
cacheKey?: string
): Promise<FetchResult<SingleProductResult>> {
const redisClient = context.client.redisTagClient;
const apolloClient = context.client.apollo as ApolloClient<any>;

let cachedProduct = null;
if (cacheKey && redisClient && (cachedProduct = await redisClient.get(cacheKey))) {
return cachedProduct;
}

const { getProductTemplate } = context.extendQuery(
customQuery, { getProductTemplate: { query, variables: params } }
);
Expand All @@ -22,5 +31,15 @@ export default async function getProductTemplate(
errorPolicy: 'all'
});

delete response?.data?.cookie;
if (cacheKey && redisClient && response.data?.product) {
redisClient.set(
cacheKey,
response,
[`API-P${response.data.product.id}`],
{ timeout: process.env.REDIS_TTL_CACHE_MAXIMUM ? randomIntegerBetween(Number(process.env.REDIS_TTL_CACHE_MINIMUM), Number(process.env.REDIS_TTL_CACHE_MAXIMUM)) : 86400 }
);
}

return response;
}
25 changes: 23 additions & 2 deletions packages/api-client/src/api/getProductTemplatesList/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,44 @@ import ApolloClient from 'apollo-client';
import query from './getProductTemplateListQuery';
import { GraphQlGetProductParams, ProductResult } from '../../index';
import { FetchResult } from 'apollo-link/lib/types';
import { randomIntegerBetween } from '../../';
export default async function getProductTemplatesList(
context: Context,
params: GraphQlGetProductParams,
customQuery?: CustomQuery
customQuery?: CustomQuery,
cacheKey?: string,
categoryIdForCache?: string
): Promise<FetchResult<ProductResult>> {
const redisClient = context.client.redisTagClient;
const apolloClient = context.client.apollo as ApolloClient<any>;

let cachedProducts = null;
if (cacheKey && redisClient && (cachedProducts = await redisClient.get(cacheKey))) {
return cachedProducts;
}

const { getProductTemplatesList } = context.extendQuery(
customQuery, { getProductTemplatesList: { query, variables: params } }
);

const response = await apolloClient.query({
query: gql`${getProductTemplatesList.query}`,
variables: getProductTemplatesList.variables,
fetchPolicy: 'no-cache',
errorPolicy: 'all'
});

delete response?.data?.cookie;
if (cacheKey &&
redisClient &&
response.data?.products &&
response.data?.products.length > 0 &&
categoryIdForCache) {
redisClient.set(
cacheKey,
response,
[`API-C${categoryIdForCache}-products`],
{ timeout: process.env.REDIS_TTL_CACHE_MAXIMUM ? randomIntegerBetween(Number(process.env.REDIS_TTL_CACHE_MINIMUM), Number(process.env.REDIS_TTL_CACHE_MAXIMUM)) : 86400 });
}

return response;
}
16 changes: 11 additions & 5 deletions packages/api-client/src/extensions/cookieExtension.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { ApiClientExtension } from '@vue-storefront/core';
import type { Request, Response } from 'express';
import requestIp from 'request-ip';

const cookieExtension: ApiClientExtension = {
name: 'cookieExtension',
hooks: (req: Request, res: Response) => {

return {
beforeCreate: ({ configuration }) => ({
...configuration,
auth: req.headers.cookie,
'resquest-host': req.headers.host
}),
beforeCreate: ({ configuration }) => {
const clientIp = requestIp.getClientIp(req);

return {
...configuration,
auth: req.headers.cookie,
'resquest-host': req.headers.host,
'real-ip': clientIp
};
},
beforeCall: ({ configuration, callName, args }) => args,
afterCall: ({ configuration, callName, response }) => {

Expand Down
1 change: 1 addition & 0 deletions packages/api-client/src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as randomIntegerBetween } from './randomIntegerBetween';
3 changes: 3 additions & 0 deletions packages/api-client/src/helpers/randomIntegerBetween.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default (min: number, max: number) : number =>{
return (Math.random() * (max - min + 1) | 0) + min;
};
1 change: 1 addition & 0 deletions packages/api-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './types/types';
export * from './types/API';
export * from './fragments';
export * from './helpers';
26 changes: 12 additions & 14 deletions packages/api-client/src/setup/apolloClient.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable quote-props */
/* eslint-disable camelcase */
import { createHttpLink } from 'apollo-link-http';
import { ApolloLink } from 'apollo-link';
import { Config } from './config';
import { onError } from 'apollo-link-error';
import fetch from 'isomorphic-fetch';
import logBuilder from './logBuilder';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const createOddoLink = (settings: Config): any => {
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.warn(
`%c [GraphQL error]: Message: ${message}, Location: ${locations.map(
(item) => `line: ${item.line} | column: ${item.column}`
)}).join(' '), Path: ${path}`,
'background: #222; color: #FFA07A'
)
);

if (networkError) console.warn(`[Network error]: ${networkError}`);

const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
graphQLErrors.map((error) => logBuilder({label: '[GRAPHQL ERROR]', ...error, operation }));
}

if (networkError) {
logBuilder({ label: '[NETWORK ERROR]', message: networkError });
}
});

const afterwareLink = new ApolloLink((operation, forward) => {
Expand All @@ -42,8 +41,7 @@ const createOddoLink = (settings: Config): any => {
headers: {
Cookie: settings.auth,
'resquest-host': settings['resquest-host'],
'X-Real-IP': settings['client-ip'],
'REMOTE_ADDR': settings['client-ip']
'REAL-IP': settings['real-ip']

}
});
Expand Down
35 changes: 28 additions & 7 deletions packages/api-client/src/setup/clientSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ import { createOddoLink } from './apolloClient';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { Config, ClientInstance } from './config';
import { Logger } from 'winston';
import Redis from 'redis-tag-cache';

const onCreate = (settings: Config): { config: Config; client: ClientInstance } => {
const logger : Logger = (process as any).winstonLog;

const config = (settings as any) as Config;
if (!logger) {
console.error('YOU MUST INSTALL AND CONFIGURE NUXT WINSTON MODULE FROM https://github.com/aaronransley/nuxt-winston-log');
throw new Error('YOU MUST INSTALL AND CONFIGURE NUXT WINSTON MODULE FROM https://github.com/aaronransley/nuxt-winston-log');
}

// if (config.payment?.providers.length === 0) {
// console.warn(
// '%c [Config error]: Message: You must set payment providers on middleware config',
// 'background: #222; color: #FFA07A'
// );
// }
const config = (settings as any) as Config;

const { apolloLink } = createOddoLink(config);

Expand All @@ -21,10 +23,29 @@ const onCreate = (settings: Config): { config: Config; client: ClientInstance }
cache: new InMemoryCache(),
...settings
});
let redisTagClient = null;

if (settings.redisClient) {
const options = {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD || null,
db: process.env.REDIS_DATABASE || 0
};

if ((process as any).superRedis) {
redisTagClient = (process as any).superRedis;
} else {
(process as any).superRedis = new Redis({ redis: options });
redisTagClient = (process as any).superRedis;
}

}

return {
config,
client: {
redisTagClient,
apollo: apolloClient
}
};
Expand Down
1 change: 1 addition & 0 deletions packages/api-client/src/setup/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface Config<T = any> {
graphqlBaseUrl: string;
odooBaseUrl: string;
cookies: CookiesConfig;
redisClient: boolean;
client?: ApolloClient<T>;
api: ApiConfig;
customOptions?: ApolloClientOptions<any>;
Expand Down
39 changes: 39 additions & 0 deletions packages/api-client/src/setup/logBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { DocumentNode } from 'apollo-link';
import { Logger } from 'winston';

interface LooseObject {
label?: string,
message?: string | Error,
location?: string,
path?: any,
query?: string,
variables?: string,
locations?: any,
operation?: any,
}

function getGqlString(doc: DocumentNode) {
return doc.loc && doc.loc.source.body?.replaceAll('\n', '');
}

export default ({ label, message, locations, path, operation }: LooseObject) : void=> {
const logger : Logger = (process as any).winstonLog;

const log : LooseObject = {
label,
message: message,
path: path
};

if (locations) {
log.location = locations?.map(item => `line: ${item.line} | column: ${item.column}`).join(' ');
}

if (process.env.NODE_LOG_LEVEL === 'TRACE') {
log.query = getGqlString(operation.query);
log.variables = operation.variables;
}

logger.error(log);
};
6 changes: 3 additions & 3 deletions packages/api-client/src/types/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import {
} from './types';

export interface OdooApiMethods {
getCategory(params: GraphQlGetCategoryParams, customQuery?: CustomQuery): Promise<FetchResult<CategoryResult>>;
getCategory(params: GraphQlGetCategoryParams, customQuery?: CustomQuery, cacheKey?: string): Promise<FetchResult<CategoryResult>>;
getCategories(params: GraphQlGetCategoriesParams, customQuery?: CustomQuery): Promise<FetchResult<CategoriesResult>>;
getProductTemplatesList(params: GraphQlGetProductParams, customQuery?: CustomQuery): Promise<FetchResult<ProductResult>>;
getProductTemplate(params: GraphQlGetProductTemplateParams, customQuery?: CustomQuery): Promise<FetchResult<SingleProductResult>>;
getProductTemplatesList(params: GraphQlGetProductParams, customQuery?: CustomQuery, cacheKey?: string, categoryIdForCache?: string): Promise<FetchResult<ProductResult>>;
getProductTemplate(params: GraphQlGetProductTemplateParams, customQuery?: CustomQuery, cacheKey?: string): Promise<FetchResult<SingleProductResult>>;
getRealProduct(params: GraphQlGetProductVariantParams, customQuery?: CustomQuery): Promise<FetchResult<ProductVariantResult>>;

updateAccount(params: GraphQlUpdateAccountParams, customQuery?: CustomQuery): Promise<FetchResult>;
Expand Down
4 changes: 3 additions & 1 deletion packages/api-client/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export type CartRemoveItemResult = {
};

export type ApplyCoupon = {
applied: boolean
error: boolean
}

export type ApplyCouponResult = {
Expand Down Expand Up @@ -596,6 +596,8 @@ export type GraphQlWishlistAddItemParams = {

export type GraphQlGetProductTemplateParams = {
id: number;
slug: string;
cacheKey: string;
};

export type GraphQlWishlistRemoveItemParams = {
Expand Down
Loading

0 comments on commit 8a1a094

Please sign in to comment.