Skip to content

Commit

Permalink
Merge pull request #48 from diggsweden/graphql-codegen
Browse files Browse the repository at this point in the history
Replacing Apollo CLi with Graphql codegen
  • Loading branch information
dajjen authored Oct 6, 2023
2 parents 2579546 + 4babff3 commit 6f7dbc5
Show file tree
Hide file tree
Showing 254 changed files with 10,485 additions and 14,730 deletions.
4 changes: 3 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
{
"extends": "next/core-web-vitals",
"plugins": ["prettier"],
"rules": {
"no-console": ["error", { "allow": ["warn", "error"] }],
"react-hooks/exhaustive-deps": "off",
"@next/next/no-sync-scripts" : "off",
"no-unused-vars": 2
"no-unused-vars": 2,
"prettier/prettier": "error"
}
}
17 changes: 17 additions & 0 deletions .yarn/plugins/@yarnpkg/plugin-npm-audit-fix.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */
//prettier-ignore
module.exports = {
name: "@yarnpkg/plugin-npm-audit-fix",
factory: function (require) {
var plugin=(()=>{var k=Object.create;var m=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,L=Object.prototype.hasOwnProperty;var v=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(c,e)=>(typeof require<"u"?require:c)[e]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var M=(r,c)=>{for(var e in c)m(r,e,{get:c[e],enumerable:!0})},x=(r,c,e,s)=>{if(c&&typeof c=="object"||typeof c=="function")for(let i of P(c))!L.call(r,i)&&i!==e&&m(r,i,{get:()=>c[i],enumerable:!(s=I(c,i))||s.enumerable});return r};var N=(r,c,e)=>(e=r!=null?k(S(r)):{},x(c||!r||!r.__esModule?m(e,"default",{value:r,enumerable:!0}):e,r)),U=r=>x(m({},"__esModule",{value:!0}),r);var T={};M(T,{Environment:()=>y,Severity:()=>w,default:()=>j});var D=v("stream"),A=v("@yarnpkg/cli"),t=v("@yarnpkg/core"),l=v("clipanion"),n=N(v("typanion")),g=class extends A.BaseCommand{constructor(){super(...arguments);this.all=l.Option.Boolean("-A,--all",!1,{description:"Audit dependencies from all workspaces"});this.recursive=l.Option.Boolean("-R,--recursive",!1,{description:"Audit transitive dependencies as well"});this.environment=l.Option.String("--environment",y.All,{description:"Which environments to cover",validator:n.isEnum(y)});this.severity=l.Option.String("--severity",w.Info,{description:"Minimal severity requested for packages to be displayed",validator:n.isEnum(w)});this.excludes=l.Option.Array("--exclude",[],{description:"Array of glob patterns of packages to exclude from audit"});this.ignores=l.Option.Array("--ignore",[],{description:"Array of glob patterns of advisory ID's to ignore in the audit report"});this.mode=l.Option.String("--mode",{description:"Change what artifacts installs generate",validator:n.isEnum(t.InstallMode)})}async execute(){let e=await this.initState(),{configuration:s,project:i,cache:o}=e;return(await t.StreamReport.start({configuration:s,stdout:this.context.stdout},async a=>{let u=await a.startTimerPromise("Audit step",()=>this.getAdvisories());for(let p of u){let f=t.structUtils.prettyIdent(s,t.structUtils.parseIdent(p.module_name)),b=t.structUtils.prettyRange(s,p.vulnerable_versions),h=t.structUtils.prettyRange(s,p.patched_versions);await a.startTimerPromise(`Advisory for ${f} at ${b}, patched at ${h}`,()=>this.handleAdvisory(a,e,p))}await i.install({report:a,cache:o,mode:this.mode})})).exitCode()}async handleAdvisory(e,s,i){let{configuration:o,resolver:d,project:a}=s,u=t.structUtils.parseIdent(i.module_name);for(let p of a.storedDescriptors.values()){if(!t.structUtils.areIdentsEqual(p,u)||t.structUtils.isVirtualDescriptor(p))continue;let f=a.storedPackages.get(a.storedResolutions.get(p.descriptorHash));if(!f||!t.semverUtils.satisfiesWithPrereleases(f.version,i.vulnerable_versions))continue;e.reportInfo(t.MessageName.UNNAMED,`Found vulnerable ${t.structUtils.prettyLocator(o,f)} (via ${t.structUtils.prettyRange(o,p.range)})`);let h=(await d.getCandidates(p,new Map,{project:a,report:e,resolver:d}))[0];if(!h){e.reportError(t.MessageName.UNNAMED,`No candidates found for ${t.structUtils.prettyDescriptor(o,p)}`);continue}let R=await d.resolve(h,{project:a,report:e,resolver:d});if(!t.semverUtils.satisfiesWithPrereleases(R.version,i.patched_versions)){e.reportWarning(t.MessageName.UNNAMED,`No compatible patched version found for ${t.structUtils.prettyDescriptor(o,p)}`);continue}e.reportInfo(t.MessageName.UNNAMED,`Setting resolution for ${t.structUtils.prettyDescriptor(o,p)} to ${t.structUtils.prettyLocator(o,h)}`),this.setResolution(s,p,R)}}setResolution(e,s,i){let{project:o}=e,d=t.structUtils.convertLocatorToDescriptor(i);o.storedDescriptors.set(s.descriptorHash,s),o.storedDescriptors.set(d.descriptorHash,d),o.resolutionAliases.set(s.descriptorHash,d.descriptorHash)}async initState(){let e=await t.Configuration.find(this.context.cwd,this.context.plugins),{project:s,workspace:i}=await t.Project.find(e,this.context.cwd),o=await t.Cache.find(e);if(!i)throw new A.WorkspaceRequiredError(s.cwd,this.context.cwd);await s.restoreInstallState();let d=e.makeResolver();return{configuration:e,workspace:i,cache:o,project:s,resolver:d}}async getAdvisories(){let e=new D.PassThrough,s=[];e.on("data",a=>{s.push(a)});let i=["npm","audit","-AR","--json"];this.all&&i.push("--all"),this.recursive&&i.push("--recursive"),this.environment&&i.push("--environment",this.environment),this.severity&&i.push("--severity",this.severity);for(let a of this.excludes)i.push("--exclude",a);for(let a of this.ignores)i.push("--ignore",a);await this.cli.run(i,{stdout:e}),e.end();let o=JSON.parse(Buffer.concat(s).toString());if(!_(o))throw new Error("Unexpected yarn npm audit result");let d=[];for(let[a,u]of Object.entries(o.advisories))d.push(u);return d}};g.paths=[["npm","audit","fix"]],g.usage=l.Command.Usage({description:"Attempt to fix advisories reported by the audit",details:`
This command attempts to resolve security advisories on the packages you use
by upgrading packages to patched versions if possible while respecting the
requested version ranges.
Most flags do the same as their counterparts in \`yarn npm audit\`.
The \`--mode\` flag does the same as its counterpart in \`yarn install\`.
`,examples:[["Attempt to resolve all audit advisories","$0 npm audit -AR"]]});var _=n.isObject({advisories:n.isDict(n.isObject({module_name:n.isString(),vulnerable_versions:n.isString(),patched_versions:n.isString()},{extra:n.isDict(n.isUnknown())}))},{extra:n.isDict(n.isUnknown())}),y=(s=>(s.All="all",s.Production="production",s.Development="development",s))(y||{}),w=(o=>(o.Info="info",o.Low="low",o.Moderate="moderate",o.High="high",o.Critical="critical",o))(w||{}),$={commands:[g]},j=$;return U(T);})();
return plugin;
}
};
801 changes: 0 additions & 801 deletions .yarn/releases/yarn-3.2.4.cjs

This file was deleted.

874 changes: 874 additions & 0 deletions .yarn/releases/yarn-3.6.3.cjs

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
- path: .yarn/plugins/@yarnpkg/plugin-npm-audit-fix.cjs
spec: "https://raw.githubusercontent.com/sargunv/yarn-plugin-npm-audit-fix/yarn-v3/bundles/%40yarnpkg/plugin-npm-audit-fix.js"

yarnPath: .yarn/releases/yarn-3.2.4.cjs
yarnPath: .yarn/releases/yarn-3.6.3.cjs
10 changes: 0 additions & 10 deletions apollo.config.js

This file was deleted.

67 changes: 67 additions & 0 deletions codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
overwrite: true,
schema: process.env.APOLLO_URL,
documents: ["./graphql/*.ts"],
generates: {
"graphql/__generated__/types.ts": {
plugins: [
{
add: {
content:
"/** THIS FILE IS AUTO-GENERATED **/\n" +
"/** DO NOT EDIT **/\n" +
"/* eslint-disable */",
},
},
"typescript",
],
config: {
avoidOptionals: {
field: true,
},
nonOptionalTypename: true,
declarationKind: "interface",
onlyOperationTypes: true,
},
},
"graphql/__generated__/operations.ts": {
preset: "import-types",
plugins: [
{
add: {
content:
"/** THIS FILE IS AUTO-GENERATED **/\n" +
"/** DO NOT EDIT **/\n" +
"/* eslint-disable */",
},
},
"typescript-operations",
],
presetConfig: {
typesPath: "./types",
},
config: {
avoidOptionals: {
field: true,
},
nonOptionalTypename: true,
skipTypeNameForRoot: true,
declarationKind: "interface",
arrayInputCoercion: false,
onlyOperationTypes: true,
// omitOperationSuffix: true,
exportFragmentSpreadSubTypes: true,
},
},
"graphql/schema.json": {
plugins: ["introspection"],
config: {
schemaDescription: true,
},
},
},
};

export default config;
26 changes: 15 additions & 11 deletions components/ApiExploring/ApiExplorer.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useContext } from 'react';
import { EnvSettings } from '../../env/EnvSettings';
import { ApiIndexContext } from './ApiIndexContext';
import dynamic from 'next/dynamic';
import React, { useContext } from "react";
import { EnvSettings } from "../../env/EnvSettings";
import { ApiIndexContext } from "./ApiIndexContext";
import dynamic from "next/dynamic";

export interface ApiExplorerProps {
env: EnvSettings;
Expand All @@ -10,18 +10,22 @@ export interface ApiExplorerProps {
}

export const ApiExplorer: React.FC<ApiExplorerProps> = (props) => {

const SwaggerUI = dynamic(() =>
import('swagger-ui-react').then(
(c) => c.default,
(e) => e as any
), {ssr: false}
const SwaggerUI = dynamic(
() =>
import("swagger-ui-react").then(
(c) => c.default,
(e) => e as any,
),
{ ssr: false },
);

const apiIndexContext = useContext(ApiIndexContext);

const getAPiDetectionUrl = () => {
var detection = apiIndexContext.findDetection(props.contextId, props.entryId);
var detection = apiIndexContext.findDetection(
props.contextId,
props.entryId,
);

if (detection && detection.apiDefinition) return detection.apiDefinition;

Expand Down
7 changes: 4 additions & 3 deletions components/ApiExploring/ApiIndexContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ export interface ApiIndex {
list: (contextid: string, entryid: string) => ApiIndexItem[] | undefined;
findDetection: (
contextid: string,
entryid: string
entryid: string,
) => ApiSpecDetection | undefined;
loading: boolean;
}

/* eslint-enable no-unused-vars */

export interface ApiIndexItem {
Expand Down Expand Up @@ -51,7 +52,7 @@ export const ApiIndexProvider: React.FC<ApiIndexProviderProps> = ({

const listByContainer = (
contextid: string,
containerEntryId: string
containerEntryId: string,
): ApiIndexItem[] => {
let result: ApiIndexItem[] = [];

Expand All @@ -73,7 +74,7 @@ export const ApiIndexProvider: React.FC<ApiIndexProviderProps> = ({

const findFirstMatch = (
contextid: string,
entryid: string
entryid: string,
): ApiSpecDetection | undefined => {
let result: ApiSpecDetection | undefined = undefined;

Expand Down
4 changes: 2 additions & 2 deletions components/ApiExploring/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './ApiExplorer';
export * from './ApiIndexContext';
export * from "./ApiExplorer";
export * from "./ApiIndexContext";
95 changes: 34 additions & 61 deletions components/ContentArea/ContentArea.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { css, Heading } from '@digg/design-system';
import React from 'react';
import { css, Heading } from "@digg/design-system";
import React from "react";
import {
Containers_dataportal_Digg_Containers_blocks,
Containers_dataportal_Digg_Containers_blocks_dataportal_Digg_ModuleList,
Containers_dataportal_Digg_Containers_blocks_dataportal_Digg_Faq as FAQ,
} from '../../graphql/__generated__/Containers';
import { RelatedContent as IRelatedContent } from '../../graphql/__generated__/RelatedContent';
import { Module_dataportal_Digg_Module_blocks as Module_blocks } from '../../graphql/__generated__/Module';
import { Faq, RelatedContent, Media, Text, Form } from '../blocks';
import Modules from './Modules';
ContainerData_Dataportal_Digg_Container_Fragment,
ModuleListDataFragment,
FaqFragment,
} from "../../graphql/__generated__/operations";
import { ModuleDataFragment } from "../../graphql/__generated__/operations";
import { Faq, RelatedContent, Media, Text, Form } from "../blocks";
import Modules from "./Modules";

interface ContentAreaProps {
blocks: (Containers_dataportal_Digg_Containers_blocks | Module_blocks | null)[];
blocks:
| ContainerData_Dataportal_Digg_Container_Fragment["blocks"]
| ModuleDataFragment["blocks"];
}

/**
Expand All @@ -20,34 +21,25 @@ interface ContentAreaProps {
* @param pos the position of the FAQ
* @returns FaqBlocks wrapped in <dl> element
*/
const handleFaqs = (
blocks: (Containers_dataportal_Digg_Containers_blocks | Module_blocks | null)[],
pos: number
) => {
const handleFaqs = (blocks: ContentAreaProps["blocks"], pos: number) => {
// skip rendering if previous block was FAQ
// because then in should already be rendered
const previousBlock = blocks[pos - 1];
if (previousBlock?.__typename === 'dataportal_Digg_Faq') return;
if (previousBlock?.__typename === "dataportal_Digg_Faq") return;

let i = 0;
// count the number of FAQs to render from the given position
while (blocks[pos + i]?.__typename === 'dataportal_Digg_Faq' || i > 500) {
while (blocks[pos + i]?.__typename === "dataportal_Digg_Faq" || i > 500) {
i++;
}

// make a copy of the FAQ range to render
const faqGroup = (blocks as FAQ[]).slice(pos, pos + i);
const faqGroup = blocks.slice(pos, pos + i);

return (
<dl
className="faqblock"
key={`content-${pos}-${faqGroup[0].id}`}
>
<dl className="faqblock" key={`content-${pos}-${faqGroup[0].id}`}>
{faqGroup.map((faq) => (
<Faq
{...faq}
key={faq?.id}
/>
<Faq {...(faq as FaqFragment)} key={faq?.id} />
))}
</dl>
);
Expand All @@ -57,44 +49,28 @@ export const ContentArea: React.FC<ContentAreaProps> = ({ blocks }) => {
return (
<>
{blocks?.map((block, index) => {
if (block == null) {
return;
}
const { id } = block || {};
switch (block?.__typename) {
case 'dataportal_Digg_Text':
return (
<Text
{...block}
key={id}
/>
);
case 'dataportal_Digg_Media':
return (
<Media
{...block}
key={id}
/>
);
case 'dataportal_Digg_Faq':
switch (block.__typename) {
case "dataportal_Digg_Text":
return <Text {...block} key={id} />;
case "dataportal_Digg_Media":
return <Media {...block} key={id} />;
case "dataportal_Digg_Faq":
return handleFaqs(blocks, index);
case 'dataportal_Digg_RelatedContent':
return (
<RelatedContent
{...(block as IRelatedContent)}
key={id}
/>
);
case 'dataportal_Digg_ModuleList':
const typedBlock =
block as Containers_dataportal_Digg_Containers_blocks_dataportal_Digg_ModuleList;
case "dataportal_Digg_RelatedContent":
return <RelatedContent {...block} key={id} />;
case "dataportal_Digg_ModuleList":
const typedBlock = block as ModuleListDataFragment;
return (
typedBlock.modules &&
typedBlock.modules.map((module) => (
<Modules
{...module}
key={module.identifier}
/>
<Modules {...module} key={module.identifier} />
))
);
case 'dataportal_Digg_FormBlock':
case "dataportal_Digg_FormBlock":
return (
<Form
key={block.id}
Expand All @@ -107,10 +83,7 @@ export const ContentArea: React.FC<ContentAreaProps> = ({ blocks }) => {
default:
return (
<div key={id}>
<Heading
level={2}
lang="en"
>
<Heading level={2} lang="en">
<>{(block as any)?.__typename} Not found</>
</Heading>
<pre
Expand Down
10 changes: 4 additions & 6 deletions components/ContentArea/Modules.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import React from 'react';
import { Containers_dataportal_Digg_Containers_blocks_dataportal_Digg_ModuleList_modules } from '../../graphql/__generated__/Containers';
import ContentArea from './ContentArea';
import React from "react";
import { ModuleDataFragment } from "../../graphql/__generated__/operations";
import ContentArea from "./ContentArea";

export const Modules: React.FC<
Containers_dataportal_Digg_Containers_blocks_dataportal_Digg_ModuleList_modules
> = ({ blocks }) => {
export const Modules: React.FC<ModuleDataFragment> = ({ blocks }) => {
return <ContentArea blocks={blocks || []} />;
};

Expand Down
4 changes: 2 additions & 2 deletions components/ContentArea/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './ContentArea';
export * from './Modules';
export * from "./ContentArea";
export * from "./Modules";
Loading

0 comments on commit 6f7dbc5

Please sign in to comment.