Skip to content

Commit

Permalink
feat: docs
Browse files Browse the repository at this point in the history
  • Loading branch information
enkot committed Sep 20, 2023
1 parent 5ef1c26 commit a30b0e2
Show file tree
Hide file tree
Showing 61 changed files with 11,708 additions and 1,862 deletions.
1 change: 0 additions & 1 deletion .nuxtrc
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
imports.autoImport=false
typescript.includeWorkspace=true
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Find and replace all on all files (CMD+SHIFT+F):
- Package name: my-module
- Description: My new Nuxt module
-->
[![Nuxt Open Fetch](./docs/public/cover.png)](https://open-fetch.nuxtjs.org)

# Nuxt Open Fetch

Expand All @@ -16,9 +17,10 @@ Find and replace all on all files (CMD+SHIFT+F):

Generate zero-overhead, typed OpenAPI clients for Nuxt.

In other words - familiar `$fetch` and `useFetch`, but for OpenAPI requests. Uses awesome [openapi-typescript](https://github.com/drwpow/openapi-typescript) generator under the hood.
In other words - `$fetch` and `useFetch` on steroids. Uses awesome [openapi-typescript](https://github.com/drwpow/openapi-typescript) generator under the hood.

- [ Release Notes](/CHANGELOG.md)
- [📖  Read the documentation](https://strapi.nuxtjs.org)
<!-- - [🏀 Online playground](https://stackblitz.com/github/your-org/my-module?file=playground%2Fapp.vue) -->
<!-- - [📖 &nbsp;Documentation](https://example.com) -->

Expand Down Expand Up @@ -85,7 +87,7 @@ npm run release

## License

Made with ❤️
Made with 💚

Published under the [MIT License](./LICENCE).

Expand Down
7 changes: 7 additions & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
externals: [
'ofetch'
]
})
24 changes: 22 additions & 2 deletions dist/module.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,22 @@
export * from "/Users/tarasbatenkov/Projects/nuxt-open-fetch/src/module";
export { default } from "/Users/tarasbatenkov/Projects/nuxt-open-fetch/src/module";
import * as _nuxt_schema from '@nuxt/schema';
import { Readable } from 'node:stream';
import { FetchOptions } from 'ofetch';
import { OpenAPITSOptions, OpenAPI3 } from 'openapi-typescript';

type OpenAPI3Schema = string | URL | OpenAPI3 | Readable;
interface OpenFetchOptions extends Omit<FetchOptions, 'method' | 'params'> {
}
interface SerializableOpenFetchOptions extends Omit<OpenFetchOptions, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'parseResponse' | 'body' | 'signal'> {
}
interface OpenFetchClientOptions {
schema?: OpenAPI3Schema;
fetchOptions?: SerializableOpenFetchOptions;
functionSuffix?: string;
}
interface ModuleOptions {
clients?: Record<string, OpenFetchClientOptions>;
openAPITS?: OpenAPITSOptions;
}
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;

export { type ModuleOptions, type OpenFetchClientOptions, type OpenFetchOptions, type SerializableOpenFetchOptions, _default as default };
2 changes: 1 addition & 1 deletion dist/module.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"compatibility": {
"nuxt": "^3.0.0"
},
"version": "0.0.1"
"version": "0.0.2"
}
141 changes: 137 additions & 4 deletions dist/module.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,139 @@
import jiti from "file:///Users/tarasbatenkov/Projects/nuxt-open-fetch/node_modules/.pnpm/[email protected]/node_modules/jiti/lib/index.js";
import { existsSync } from 'node:fs';
import { defineNuxtModule, createResolver, addTypeTemplate, addImportsSources, addTemplate, addPlugin, addImports } from '@nuxt/kit';
import openapiTS from 'openapi-typescript';
import { kebabCase, pascalCase, camelCase } from 'scule';
import { defu } from 'defu';

/** @type {import("/Users/tarasbatenkov/Projects/nuxt-open-fetch/src/module")} */
const _module = jiti(null, { interopDefault: true, esmResolve: true })("/Users/tarasbatenkov/Projects/nuxt-open-fetch/src/module.ts");
const isValidUrl = (url) => {
try {
return Boolean(new URL(url));
} catch (e) {
return false;
}
};

export default _module;
const moduleName = "nuxt-open-fetch";
const module = defineNuxtModule({
meta: {
name: moduleName,
configKey: "openFetch",
compatibility: {
nuxt: "^3.0.0"
}
},
async setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url);
const schemas = [];
for (const layer of nuxt.options._layers) {
const { srcDir, openFetch: options2 } = layer.config;
const schemasDir = resolve(srcDir, "openapi");
for (const [name, config] of Object.entries(options2?.clients || {})) {
if (schemas.some((item) => item.name === name) || !config)
continue;
let schema = void 0;
if (config.schema && typeof config.schema === "string") {
schema = isValidUrl(config.schema) ? config.schema : resolve(srcDir, config.schema);
} else {
const jsonPath = resolve(schemasDir, `${name}/openapi.json`);
const yamlPath = resolve(schemasDir, `${name}/openapi.yaml`);
schema = existsSync(jsonPath) ? jsonPath : existsSync(yamlPath) ? yamlPath : void 0;
}
if (!schema)
throw new Error(`Could not find OpenAPI schema for "${name}"`);
schemas.push({
name,
fetchName: {
raw: getClientName(name, { suffix: config.functionSuffix }),
composable: getClientName(name, { suffix: config.functionSuffix, isComposable: true }),
lazyComposable: getClientName(name, { suffix: config.functionSuffix, isComposable: true, lazy: true })
},
schema,
openAPITS: options2?.openAPITS
});
}
}
nuxt.options.runtimeConfig.public.openFetch = defu(nuxt.options.runtimeConfig.public.openFetch, options);
nuxt.options.optimization = nuxt.options.optimization || {
keyedComposables: []
};
nuxt.options.optimization.keyedComposables = [
...nuxt.options.optimization.keyedComposables,
...schemas.flatMap(({ fetchName }) => [
{ name: fetchName.composable, argumentLength: 3 },
{ name: fetchName.lazyComposable, argumentLength: 3 }
])
];
for (const { name, schema, openAPITS } of schemas) {
addTypeTemplate({
filename: `types/${moduleName}/${kebabCase(name)}.d.ts`,
getContents: () => openapiTS(schema, openAPITS)
});
}
addImportsSources({
from: resolve(nuxt.options.buildDir, `module/${moduleName}.mjs`),
imports: schemas.flatMap(({ fetchName }) => Object.values(fetchName))
});
addTemplate({
filename: `module/${moduleName}.mjs`,
getContents() {
return `
import { createOpenFetchClient, createUseOpenFetchClient, createUseLazyOpenFetchClient } from '${resolve("clients")}'
${schemas.map(({ name, fetchName }) => `
export const ${fetchName.raw} = createOpenFetchClient('${name}')
export const ${fetchName.composable} = createUseOpenFetchClient('${name}')
export const ${fetchName.lazyComposable} = createUseLazyOpenFetchClient('${name}')
`.trimStart()).join("\n")}`.trimStart();
},
write: true
});
addTemplate({
filename: `module/${moduleName}.d.ts`,
getContents() {
return `
// Generated by ${moduleName}
import type { OpenFetchOptions } from '${resolve("module")}'
import type { OpenFetchClient, UseOpenFetchClient, UseLazyOpenFetchClient } from '${resolve("clients")}'
${schemas.map(({ name }) => `
import type { paths as ${pascalCase(name)}Paths } from '#build/types/${moduleName}/${kebabCase(name)}'
`.trimStart()).join("").trimEnd()}
export type OpenFetchClientName = ${schemas.map(({ name }) => `'${name}'`).join(" | ")}
declare module '#app' {
interface NuxtApp {
$openFetch: Record<OpenFetchClientName, OpenFetchOptions>
}
}
declare module 'vue' {
interface ComponentCustomProperties {
$openFetch: Record<OpenFetchClientName, OpenFetchOptions>
}
}
${schemas.map(({ name, fetchName }) => `
export declare const ${fetchName.raw}: OpenFetchClient<${pascalCase(name)}Paths>
export declare const ${fetchName.composable}: UseOpenFetchClient<${pascalCase(name)}Paths>
export declare const ${fetchName.lazyComposable}: UseLazyOpenFetchClient<${pascalCase(name)}Paths>
`.trimStart()).join("\n").trimEnd()}
export {}
`.trimStart();
}
});
addPlugin(resolve("./runtime/plugin"));
addImports({
name: "useOpenFetchOptions",
as: "useOpenFetchOptions",
from: resolve("runtime/composables/useOpenFetchOptions")
});
function getClientName(name, { suffix = "fetch", isComposable = false, lazy = false } = {}) {
name = name === "default" ? "open" : name;
return isComposable ? `use${lazy ? "Lazy" : ""}${pascalCase(`${name}-${suffix}`)}` : `$${camelCase(`${name}-${suffix}`)}`;
}
}
});

export { module as default };
1 change: 0 additions & 1 deletion dist/runtime

This file was deleted.

10 changes: 2 additions & 8 deletions dist/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@

import { ModuleOptions, ModuleHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module'
import { ModuleOptions } from './module'

declare module '@nuxt/schema' {
interface NuxtConfig { ['openFetch']?: Partial<ModuleOptions> }
interface NuxtOptions { ['openFetch']?: ModuleOptions }
interface NuxtHooks extends ModuleHooks {}
interface RuntimeConfig extends ModuleRuntimeConfig {}
interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
}

declare module 'nuxt/schema' {
interface NuxtConfig { ['openFetch']?: Partial<ModuleOptions> }
interface NuxtOptions { ['openFetch']?: ModuleOptions }
interface NuxtHooks extends ModuleHooks {}
interface RuntimeConfig extends ModuleRuntimeConfig {}
interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
}


export { default } from './module'
export { ModuleOptions, OpenFetchClientOptions, OpenFetchOptions, SerializableOpenFetchOptions, default } from './module'
4 changes: 4 additions & 0 deletions docs/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist
node_modules
.output
.nuxt
8 changes: 8 additions & 0 deletions docs/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
root: true,
extends: '@nuxt/eslint-config',
rules: {
'vue/max-attributes-per-line': 'off',
'vue/multi-word-component-names': 'off'
}
}
12 changes: 12 additions & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
node_modules
*.iml
.idea
*.log*
.nuxt
.vscode
.DS_Store
coverage
dist
sw.*
.env
.output
1 change: 1 addition & 0 deletions docs/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
shamefully-hoist=true
57 changes: 57 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Docus Starter

Starter template for [Docus](https://docus.dev).

## Clone

Clone the repository (using `nuxi`):

```bash
npx nuxi init -t themes/docus
```

## Setup

Install dependencies:

```bash
yarn install
```

## Development

```bash
yarn dev
```

## Edge Side Rendering

Can be deployed to Vercel Functions, Netlify Functions, AWS, and most Node-compatible environments.

Look at all the available presets [here](https://v3.nuxtjs.org/guide/deploy/presets).

```bash
yarn build
```

## Static Generation

Use the `generate` command to build your application.

The HTML files will be generated in the .output/public directory and ready to be deployed to any static compatible hosting.

```bash
yarn generate
```

## Preview build

You might want to preview the result of your build locally, to do so, run the following command:

```bash
yarn preview
```

---

For a detailed explanation of how things work, check out [Docus](https://docus.dev).
30 changes: 30 additions & 0 deletions docs/app.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export default defineAppConfig({
docus: {
title: 'Nuxt Open Fetch',
description: 'Generate zero-overhead, typed OpenAPI clients for Nuxt.',
image: 'https://user-images.githubusercontent.com/904724/185365452-87b7ca7b-6030-4813-a2db-5e65c785bf88.png',
socials: {
github: 'enkot/nuxt-open-fetch',
nuxt: {
label: 'Nuxt',
icon: 'simple-icons:nuxtdotjs',
href: 'https://nuxt.com'
}
},
github: {
dir: '.starters/default/content',
branch: 'main',
repo: 'docus',
owner: 'nuxt-themes',
edit: true
},
aside: {
level: 0,
collapsed: false,
exclude: []
},
header: {
logo: true,
}
}
})
Loading

0 comments on commit a30b0e2

Please sign in to comment.