27 Commits

Author SHA1 Message Date
0dfad07399 chore(release): v0.0.9 2023-07-09 14:39:55 +03:00
e6b8b7d0fa chore: fix tsconfig for build time 2023-07-09 14:39:02 +03:00
0cdba0d764 chore: lint 2023-07-09 14:27:10 +03:00
9c0e0baf95 docs: add types link 2023-07-09 14:21:33 +03:00
925d382f2f chore: update dependencies 2023-07-09 14:16:21 +03:00
3ff97569f5 docs(utils): fix model options type 2023-07-09 14:10:34 +03:00
52a5ae9180 Merge branch 'main' of https://github.com/arashsheyda/nuxt-mongoose 2023-07-09 14:08:23 +03:00
4647fbda16 Revert "chore: fix defineNitroPlugin patch (#9)"
This reverts commit 470f272183.
2023-07-09 14:08:05 +03:00
647d26db85 docs(utils): add hooks and improve documentation 2023-07-09 13:53:11 +03:00
40b8ca91ee chore: example env 2023-07-09 13:28:28 +03:00
d92a58b2ad feat: mongoose schema hooks 2023-07-09 13:25:38 +03:00
5a43ebe06f fix: update connection message in logger (#10) 2023-07-02 12:36:48 +03:00
56259adaf7 feat: add possibility to type mongoose model (#8)
Co-authored-by: Arash <38922203+arashsheyda@users.noreply.github.com>
2023-07-02 11:55:49 +03:00
470f272183 chore: fix defineNitroPlugin patch (#9) 2023-06-28 23:15:30 +03:00
e2d37c2efe chore(release): v0.0.8 2023-06-18 13:19:46 +03:00
487cca530b chore: update cover 2023-06-18 13:09:00 +03:00
9e867fc0b3 docs: favicon 2023-06-18 13:04:06 +03:00
23ec1989f7 docs: style 2023-06-18 13:00:34 +03:00
1c3608743e fix: resource generator modelsDir output 2023-06-18 12:32:00 +03:00
33bb3cc550 fix: run studio action only for docs 2023-06-18 12:26:59 +03:00
fe1807fcd5 Merge branch 'main' of https://github.com/arashsheyda/nuxt-mongoose 2023-06-18 12:21:49 +03:00
aaef56cb29 refactor: reuse vite's websocket 2023-06-18 12:20:57 +03:00
32846c1e44 Merge pull request #6 from joypal23jkp/patch-1
Updated the configuration setup docs.
2023-06-12 10:53:36 +03:00
771e071005 Updated the configuration setup docs.
Figured out that need to just add MONGODB_URI to .env if only need to provide URI.
2023-06-12 02:12:47 +06:00
2ba8bdadfc docs(devtools): demo video 2023-06-08 22:39:03 +03:00
6c057d4cd7 docs: remove devtools 2023-06-05 21:35:37 +03:00
00259fc865 chore(deployment): add workflow file 2023-06-05 21:31:22 +03:00
28 changed files with 2322 additions and 1898 deletions

View File

@ -1,2 +1,5 @@
dist
node_modules
docs
.github
.vscode

82
.github/workflows/studio.yml vendored Normal file
View File

@ -0,0 +1,82 @@
name: studio-nuxt-build
run-name: studio nuxt build
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Add write workflow permissions
permissions:
contents: write
# Allow one concurrent deployment
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
# Build job
build-and-deploy:
if: startsWith(github.event.head_commit.message, 'docs:')
runs-on: ${{ matrix.os }}
defaults:
run:
working-directory: docs
strategy:
matrix:
os: [ubuntu-latest]
node: [18]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Identify package manager
id: pkgman
run: |
cache=`[ -f "docs/pnpm-lock.yaml" ] && echo "pnpm" || ([ -f "docs/package-lock.json" ] && echo "npm" || ([ -f "docs/yarn.lock" ] && echo "yarn" || echo ""))`
package_manager=`[ ! -z "$cache" ] && echo "$cache" || echo "pnpm"`
echo "cache=$cache" >> $GITHUB_OUTPUT
echo "package_manager=$package_manager" >> $GITHUB_OUTPUT
- uses: pnpm/action-setup@v2.2.4
if: ${{ steps.pkgman.outputs.package_manager == 'pnpm' }}
name: Install pnpm
id: pnpm-install
with:
version: 7
- uses: actions/setup-node@v3
with:
version: ${{ matrix.node }}
cache: ${{ steps.pkgman.outputs.cache }}
- name: Install dependencies
run: ${{ steps.pkgman.outputs.package_manager }} install
- name: Install @nuxthq/studio
run: ${{ steps.pkgman.outputs.package_manager }} add -D @nuxthq/studio
- name: Create .nuxtrc
run: echo 'modules[]=@nuxthq/studio' > .nuxtrc
- name: Generate
run: ${{ steps.pkgman.outputs.package_manager }} nuxi generate
env:
NUXT_PUBLIC_STUDIO_API_URL: https://api.nuxt.studio
NUXT_PUBLIC_STUDIO_TOKENS: 6222c5e49391ad99e20e3c1b1a475c656436e8b0877c32021147d8727205c440
- name: Add .nojekyll file
run: touch .output/public/.nojekyll
# Deployment job
- name: Deploy 🚀
uses: JamesIves/github-pages-deploy-action@v4
with:
folder: docs/.output/public

1
.nuxtrc Normal file
View File

@ -0,0 +1 @@
typescript.includeWorkspace=true

View File

@ -1,6 +1,79 @@
# Changelog
## v0.0.9
[compare changes](https://github.com/arashsheyda/nuxt-mongoose/compare/v0.0.8...v0.0.9)
### 🚀 Enhancements
- Add possibility to type mongoose model ([#8](https://github.com/arashsheyda/nuxt-mongoose/pull/8))
- Mongoose schema hooks ([d92a58b](https://github.com/arashsheyda/nuxt-mongoose/commit/d92a58b))
### 🩹 Fixes
- Update connection message in logger ([#10](https://github.com/arashsheyda/nuxt-mongoose/pull/10))
### 📖 Documentation
- **utils:** Add hooks and improve documentation ([647d26d](https://github.com/arashsheyda/nuxt-mongoose/commit/647d26d))
- **utils:** Fix model options type ([3ff9756](https://github.com/arashsheyda/nuxt-mongoose/commit/3ff9756))
- Add types link ([9c0e0ba](https://github.com/arashsheyda/nuxt-mongoose/commit/9c0e0ba))
### 🏡 Chore
- Fix defineNitroPlugin patch ([#9](https://github.com/arashsheyda/nuxt-mongoose/pull/9))
- Example env ([40b8ca9](https://github.com/arashsheyda/nuxt-mongoose/commit/40b8ca9))
- Fix defineNitroPlugin patch " ([#9](https://github.com/arashsheyda/nuxt-mongoose/pull/9))
- Update dependencies ([925d382](https://github.com/arashsheyda/nuxt-mongoose/commit/925d382))
- Lint ([0cdba0d](https://github.com/arashsheyda/nuxt-mongoose/commit/0cdba0d))
- Fix tsconfig for build time ([e6b8b7d](https://github.com/arashsheyda/nuxt-mongoose/commit/e6b8b7d))
### ❤️ Contributors
- Arash Sheyda <sheidaeearash1999@gmail.com>
- Arash
- Amir-al-mohamad111
- Oumar Barry ([@oumarbarry](http://github.com/oumarbarry))
## v0.0.8
[compare changes](https://github.com/arashsheyda/nuxt-mongoose/compare/v0.0.7...v0.0.8)
### 🚀 Enhancements
- Documentation ([6ca94dc](https://github.com/arashsheyda/nuxt-mongoose/commit/6ca94dc))
### 🩹 Fixes
- Module options type ([182b760](https://github.com/arashsheyda/nuxt-mongoose/commit/182b760))
- Run studio action only for docs ([33bb3cc](https://github.com/arashsheyda/nuxt-mongoose/commit/33bb3cc))
- Resource generator modelsDir output ([1c36087](https://github.com/arashsheyda/nuxt-mongoose/commit/1c36087))
### 💅 Refactors
- Reuse vite's websocket ([aaef56c](https://github.com/arashsheyda/nuxt-mongoose/commit/aaef56c))
### 📖 Documentation
- Remove devtools ([6c057d4](https://github.com/arashsheyda/nuxt-mongoose/commit/6c057d4))
- **devtools:** Demo video ([2ba8bda](https://github.com/arashsheyda/nuxt-mongoose/commit/2ba8bda))
- Style ([23ec198](https://github.com/arashsheyda/nuxt-mongoose/commit/23ec198))
- Favicon ([9e867fc](https://github.com/arashsheyda/nuxt-mongoose/commit/9e867fc))
### 🏡 Chore
- Playground example ([3356ffd](https://github.com/arashsheyda/nuxt-mongoose/commit/3356ffd))
- **deployment:** Add workflow file ([00259fc](https://github.com/arashsheyda/nuxt-mongoose/commit/00259fc))
- Update cover ([487cca5](https://github.com/arashsheyda/nuxt-mongoose/commit/487cca5))
### ❤️ Contributors
- Arash
- Arash Sheyda <sheidaeearash1999@gmail.com>
- Arashsheyda <sheidaeearash1999@gmail.com>
## v0.0.7
[compare changes](https://github.com/arashsheyda/nuxt-mongoose/compare/v0.0.6...v0.0.7)

View File

@ -1,4 +1,4 @@
![nuxt-mongoose](https://raw.githubusercontent.com/arashsheyda/nuxt-mongoose/c967d0bb162dddc27fa510ba3b49e4f9b6b2db61/docs/public/nuxt-mongoose.svg)
![nuxt-mongoose](https://nuxt-mongoose.nuxt.space/cover.jpg)
<div align="center">
<h1>Nuxt Mongoose</h1>

View File

@ -81,8 +81,9 @@ function editDocument(document: any) {
async function saveDocument(document: any, create = true) {
const method = create ? rpc.createDocument : rpc.updateDocument
const newDocument = await method(props.collection, document)
// TODO: show toast
if (newDocument?.error)
return alert(newDocument.error.message)
return
if (create) {
if (!documents.value.length) {
@ -105,8 +106,9 @@ function discardEditing() {
async function deleteDocument(document: any) {
const newDocument = await rpc.deleteDocument(props.collection, document._id)
// TODO: show toast
if (newDocument.deletedCount === 0)
return alert('Failed to delete document')
return
documents.value = documents.value.filter((doc: any) => doc._id !== document._id)
}

View File

@ -1,14 +1,15 @@
import { createBirpc } from 'birpc'
import { parse, stringify } from 'flatted'
import { createHotContext } from 'vite-hot-client'
import type { ClientFunctions, ServerFunctions } from '../../src/types'
import { PATH_ENTRY } from '../../src/constants'
const RECONNECT_INTERVAL = 2000
import { WS_EVENT_NAME } from '../../src/constants'
export const wsConnecting = ref(true)
export const wsError = ref<any>()
export const wsConnectingDebounced = useDebounce(wsConnecting, 2000)
let connectPromise = connectWS()
const connectPromise = connectVite()
// eslint-disable-next-line @typescript-eslint/ban-types
let onMessage: Function = () => {}
export const clientFunctions = {
@ -19,9 +20,11 @@ export const extendedRpcMap = new Map<string, any>()
export const rpc = createBirpc<ServerFunctions>(clientFunctions, {
post: async (d) => {
(await connectPromise).send(d)
(await connectPromise).send(WS_EVENT_NAME, d)
},
on: (fn) => {
onMessage = fn
},
on: (fn) => { onMessage = fn },
serialize: stringify,
deserialize: parse,
resolver(name, fn) {
@ -35,35 +38,22 @@ export const rpc = createBirpc<ServerFunctions>(clientFunctions, {
onError(error, name) {
console.error(`[nuxt-devtools] RPC error on executing "${name}":`, error)
},
timeout: 120_000,
})
async function connectWS() {
const wsUrl = new URL(`ws://host${PATH_ENTRY}`)
wsUrl.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
wsUrl.host = 'localhost:3000'
async function connectVite() {
const hot = await createHotContext()
const ws = new WebSocket(wsUrl.toString())
ws.addEventListener('message', e => onMessage(String(e.data)))
ws.addEventListener('error', (e) => {
console.error(e)
wsError.value = e
if (!hot)
throw new Error('Unable to connect to devtools')
hot.on(WS_EVENT_NAME, (data) => {
onMessage(data)
})
ws.addEventListener('close', () => {
// eslint-disable-next-line no-console
console.log('[nuxt-devtools] WebSocket closed, reconnecting...')
wsConnecting.value = true
setTimeout(async () => {
connectPromise = connectWS()
}, RECONNECT_INTERVAL)
})
wsConnecting.value = true
if (ws.readyState !== WebSocket.OPEN)
await new Promise(resolve => ws.addEventListener('open', resolve))
// eslint-disable-next-line no-console
console.log('[nuxt-devtools] WebSocket connected.')
wsConnecting.value = false
wsError.value = null
// TODO:
// hot.on('vite:connect', (data) => {})
// hot.on('vite:disconnect', (data) => {})
return ws
return hot
}

View File

@ -2,8 +2,9 @@ export default defineAppConfig({
docus: {
title: 'Nuxt Mongoose',
description: 'A Nuxt module for simplifying the use of Mongoose in your project.',
image: 'https://user-images.githubusercontent.com/904724/185365452-87b7ca7b-6030-4813-a2db-5e65c785bf88.png',
image: '/cover.jpg',
socials: {
twitter: 'arash_sheyda',
github: 'arashsheyda/nuxt-mongoose',
},
github: {

View File

@ -1,12 +1,18 @@
<template>
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 235.5 33.2">
<svg id="NuxtMongooseLogo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 235.5 33.2">
<rect width="32" height="32" rx="7.5" style="fill:#023430" />
<path d="M21.4,13.4C20.1,7.6,17.3,6.1,16.6,5a10.1,10.1,0,0,1-.7-1.5,1.6,1.6,0,0,1-.6,1.2,14.1,14.1,0,0,0-4.9,10.5c-.3,6.1,4.5,9.9,5.1,10.3a1.4,1.4,0,0,0,1.4-.2,12.1,12.1,0,0,0,4.5-11.9" style="fill:#10aa50" />
<path d="M16.1,22.2a17.8,17.8,0,0,1-.5,3.3s.2,1.5.3,3h.5a30.6,30.6,0,0,1,.5-3.2C16.3,25,16.1,23.6,16.1,22.2Z" style="fill:#b8c4c2" />
<path d="M16.9,25.3c-.6-.3-.8-1.7-.8-3.1s.2-4.3.1-6.5,0-10.7-.3-12.1L16.6,5c.7,1.1,3.5,2.6,4.8,8.4A12,12,0,0,1,16.9,25.3Z" style="fill:#12924f" />
<text transform="translate(32.8 25.6)" style="font-size:25.818214416503906px;font-family:OpenSans-Bold, Open Sans;font-weight:700">
<text transform="translate(32.8 25.6)" style="font-size:25.818214416503906px;font-family:var(--font-sans);font-weight:700">
<tspan fill="currentColor" x="4" y="0">Nuxt</tspan>
<tspan x="70.8" y="0" style="fill:#10aa50">Mongoose</tspan>
<tspan x="67.8" y="0" style="fill:#10aa50">Mongoose</tspan>
</text>
</svg>
</template>
<style>
.NuxtMongooseLogo {
font-family: serif;
}
</style>

View File

@ -19,7 +19,7 @@ secondary:
---
#title
Nuxt Mongoose
Nuxt [Mongoose]{style="color: var(--color-primary-500)"}
#description
A Nuxt module for simplifying the use of [Mongoose](https://mongoosejs.com/) in your project.

View File

@ -49,3 +49,8 @@ export default defineNuxtConfig({
},
})
```
If you want to configure only the `uri` just add `MONGODB_URI` in your `.env` file.
```env
MONGODB_URI=YOUR_MONGO_URI
```

View File

@ -12,13 +12,17 @@ This function creates a new Mongoose model with schema. Example usage:
export const User = defineMongooseModel({
name: 'User',
schema: {
name: {
type: String,
email: {
type: 'string',
required: true,
unique: true,
},
},
options: {
},
hooks(schema) {
},
})
```
@ -27,18 +31,31 @@ This function creates a new Mongoose model with schema. Example usage:
import { defineMongooseModel } from '#nuxt/mongoose'
export const User = defineMongooseModel('User', {
name: {
type: String,
email: {
type: 'string',
required: true,
unique: true,
},
}, {
}, (schema) => {
})
```
::
| **Key** | **Type** | **Require** | **Description** |
| ---------------------------- | ----------- | ----------- | ----- |
| `name` | `string` | true | Name of Model |
| `schema` | [`SchemaDefinition`](https://mongoosejs.com/docs/schematypes.html) | true | Schema Definition of Model |
| `options` | [`SchemaOptions`](https://mongoosejs.com/docs/guide.html#options) | false | Schema Options for Model |
| `hooks` | [`(schema: Schema<T>) => void`](https://mongoosejs.com/docs/middleware.html) | false | Schema Hooks Function to customize Model |
## `defineMongooseConnection`
This function creates a new Mongoose connection.
- `nuxt-mongoose` provides a default connection for you, it auto-register a plugin in nitro, so you don't need to use this function unless you want to create a new connection. more info [here](https://github.com/arashsheyda/nuxt-mongoose/blob/main/src/runtime/server/plugins/mongoose.db.ts).

View File

@ -1,3 +1,8 @@
# Devtools (beta)
`nuxt-mongoose` comes with a [Nuxt Devtools](https://github.com/nuxt/devtools) module that allows you to manage your collections and generate api-endpoints & schemas...
Here is a demo video:
:video-player{src="https://www.youtube.com/watch?v=hK0npSfr_Vs"}

View File

@ -1,8 +1,19 @@
export default defineNuxtConfig({
extends: '@nuxt-themes/docus',
app: {
head: {
link: [
{
rel: 'icon',
type: 'image/x-icon',
href: '/mongoose-icon.svg',
},
],
},
},
modules: [
'@nuxthq/studio',
'@nuxt/devtools',
],
})

BIN
docs/public/cover.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,7 +1,7 @@
{
"name": "nuxt-mongoose",
"type": "module",
"version": "0.0.7",
"version": "0.0.9",
"description": "Nuxt 3 module for MongoDB with Mongoose",
"license": "MIT",
"repository": {
@ -14,10 +14,6 @@
"require": "./module.cjs",
"import": "./dist/module.mjs"
},
"./types": {
"types": "./dist/types.d.ts",
"import": "./dist/types.mjs"
},
"./*": "./*"
},
"main": "./module.cjs",
@ -38,35 +34,36 @@
"test:watch": "vitest watch"
},
"dependencies": {
"@nuxt/devtools-kit": "^0.5.5",
"@nuxt/kit": "^3.5.2",
"@nuxt/devtools-kit": "^0.6.7",
"@nuxt/kit": "^3.6.2",
"@types/fs-extra": "^11.0.1",
"birpc": "^0.2.11",
"birpc": "^0.2.12",
"defu": "^6.1.2",
"flatted": "^3.2.7",
"fs-extra": "^11.1.1",
"mongoose": "^7.2.2",
"pathe": "^1.1.0",
"mongoose": "^7.3.2",
"ofetch": "^1.1.1",
"pathe": "^1.1.1",
"pluralize": "^8.0.0",
"sirv": "^2.0.3",
"tinyws": "^0.1.0",
"vite-hot-client": "^0.2.1",
"ws": "^8.13.0"
},
"devDependencies": {
"@antfu/eslint-config": "^0.38.5",
"@nuxt/devtools": "^0.5.5",
"@nuxt/devtools-ui-kit": "^0.5.5",
"@antfu/eslint-config": "^0.39.7",
"@nuxt/devtools": "^0.6.7",
"@nuxt/devtools-ui-kit": "^0.6.7",
"@nuxt/module-builder": "^0.4.0",
"@nuxt/schema": "^3.5.2",
"@nuxt/test-utils": "^3.5.2",
"@types/pluralize": "^0.0.29",
"@types/ws": "^8.5.4",
"changelogen": "^0.5.3",
"eslint": "^8.39.0",
"nuxt": "^3.5.2",
"sass": "^1.62.1",
"sass-loader": "^13.3.1",
"@nuxt/schema": "^3.6.2",
"@nuxt/test-utils": "^3.6.2",
"@types/pluralize": "^0.0.30",
"@types/ws": "^8.5.5",
"changelogen": "^0.5.4",
"eslint": "^8.44.0",
"nuxt": "^3.6.2",
"sass": "^1.63.6",
"sass-loader": "^13.3.2",
"splitpanes": "^3.1.5",
"vitest": "^0.31.2"
"vitest": "^0.33.0"
}
}

1
playground/.env.example Normal file
View File

@ -0,0 +1 @@
MONGODB_URI="mongodb://127.0.0.1:27017/nuxt-mongoose"

View File

@ -7,10 +7,20 @@ export const UserSchema = defineMongooseModel({
type: 'string',
required: true,
},
slug: {
email: {
type: 'string',
required: true,
unique: false,
},
password: {
type: 'string',
required: true,
unique: true,
},
},
hooks(schema) {
schema.pre('save', function (this, next) {
this.password = `hash.${this.password}.${Math.random()}`
next()
})
},
})

3744
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,3 @@
export const PATH = '/__nuxt_mongoose__'
export const PATH_ENTRY = `${PATH}/entry`
export const PATH_CLIENT = `${PATH}/client`
export const WS_EVENT_NAME = 'nuxt:devtools:mongoose:rpc'

View File

@ -2,17 +2,19 @@ import {
addImportsDir,
addServerPlugin,
addTemplate,
addVitePlugin,
createResolver,
defineNuxtModule,
logger,
} from '@nuxt/kit'
import { pathExists } from 'fs-extra'
import { tinyws } from 'tinyws'
import { join } from 'pathe'
import { defu } from 'defu'
import sirv from 'sirv'
import { $fetch } from 'ofetch'
import { version } from '../package.json'
import { PATH_CLIENT, PATH_ENTRY } from './constants'
import { PATH_CLIENT } from './constants'
import type { ModuleOptions } from './types'
import { setupRPC } from './server-rpc'
@ -32,7 +34,14 @@ export default defineNuxtModule<ModuleOptions>({
},
setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url)
const runtimeConfig = nuxt.options.runtimeConfig
const runtimeConfig = nuxt.options.runtimeConfig as any
if (nuxt.options.dev) {
$fetch('https://registry.npmjs.org/nuxt-mongoose/latest').then((release) => {
if (release.version > version)
logger.info(`A new version of Nuxt Mongoose (v${release.version}) is available: https://github.com/arashsheyda/nuxt-mongoose/releases/latest`)
}).catch(() => {})
}
addImportsDir(resolve('./runtime/composables'))
@ -58,11 +67,11 @@ export default defineNuxtModule<ModuleOptions>({
}
const clientPath = distResolve('./client')
const { middleware: rpcMiddleware } = setupRPC(nuxt, options)
const { vitePlugin } = setupRPC(nuxt, options)
addVitePlugin(vitePlugin)
nuxt.hook('vite:serverCreated', async (server) => {
server.middlewares.use(PATH_ENTRY, tinyws() as any)
server.middlewares.use(PATH_ENTRY, rpcMiddleware as any)
if (await pathExists(clientPath))
server.middlewares.use(PATH_CLIENT, sirv(clientPath, { dev: true, single: true }))
})

View File

@ -11,14 +11,24 @@ export async function defineMongooseConnection({ uri, options }: { uri?: string;
try {
await mongoose.connect(mongooseUri, { ...mongooseOptions })
logger.info('Connected to mongoose database')
logger.success('Connected to MongoDB database')
}
catch (err) {
logger.error('Error connecting to database', err)
logger.error('Error connecting to MongoDB database', err)
}
}
export function defineMongooseModel(nameOrOptions: string | { name: string; schema: SchemaDefinition; options?: SchemaOptions }, schema?: SchemaDefinition, options?: SchemaOptions): Model<any> {
export function defineMongooseModel<T>(
nameOrOptions: string | {
name: string
schema: SchemaDefinition
options?: SchemaOptions
hooks?: (schema: mongoose.Schema<T>) => void
},
schema?: SchemaDefinition,
options?: SchemaOptions,
hooks?: (schema: mongoose.Schema<T>) => void,
): Model<T> {
let name: string
if (typeof nameOrOptions === 'string') {
name = nameOrOptions
@ -27,10 +37,13 @@ export function defineMongooseModel(nameOrOptions: string | { name: string; sche
name = nameOrOptions.name
schema = nameOrOptions.schema
options = nameOrOptions.options
hooks = nameOrOptions.hooks
}
const newSchema = new mongoose.Schema({
...schema,
}, { ...options })
return mongoose.model(name, newSchema)
const newSchema = new mongoose.Schema<T>(schema, options as any)
if (hooks)
hooks(newSchema)
return mongoose.model<T>(name, newSchema)
}

View File

@ -1,12 +1,12 @@
import type { TinyWSRequest } from 'tinyws'
import type { NodeIncomingMessage, NodeServerResponse } from 'h3'
import type { WebSocket } from 'ws'
import { createBirpcGroup } from 'birpc'
import type { ChannelOptions } from 'birpc'
import { parse, stringify } from 'flatted'
import type { Plugin } from 'vite'
import type { Nuxt } from 'nuxt/schema'
import type { ClientFunctions, ModuleOptions, NuxtDevtoolsServerContext, ServerFunctions } from '../types'
import { WS_EVENT_NAME } from '../constants'
import { setupDatabaseRPC } from './database'
import { setupResourceRPC } from './resource'
@ -68,36 +68,50 @@ export function setupRPC(nuxt: Nuxt, options: ModuleOptions): any {
} satisfies Partial<ServerFunctions>)
const wsClients = new Set<WebSocket>()
const middleware = async (req: NodeIncomingMessage & TinyWSRequest, _res: NodeServerResponse, next: Function) => {
// Handle WebSocket
if (req.ws) {
const ws = await req.ws()
wsClients.add(ws)
const channel: ChannelOptions = {
post: d => ws.send(d),
on: fn => ws.on('message', fn),
serialize: stringify,
deserialize: parse,
}
rpc.updateChannels((c) => {
c.push(channel)
})
ws.on('close', () => {
wsClients.delete(ws)
const vitePlugin: Plugin = {
name: 'nuxt:devtools:rpc',
configureServer(server) {
server.ws.on('connection', (ws) => {
wsClients.add(ws)
const channel: ChannelOptions = {
post: d => ws.send(JSON.stringify({
type: 'custom',
event: WS_EVENT_NAME,
data: d,
})),
on: (fn) => {
ws.on('message', (e) => {
try {
const data = JSON.parse(String(e)) || {}
if (data.type === 'custom' && data.event === WS_EVENT_NAME) {
// console.log(data.data)
fn(data.data)
}
}
catch {}
})
},
serialize: stringify,
deserialize: parse,
}
rpc.updateChannels((c) => {
const index = c.indexOf(channel)
if (index >= 0)
c.splice(index, 1)
c.push(channel)
})
ws.on('close', () => {
wsClients.delete(ws)
rpc.updateChannels((c) => {
const index = c.indexOf(channel)
if (index >= 0)
c.splice(index, 1)
})
})
})
}
else {
next()
}
},
}
return {
middleware,
vitePlugin,
...ctx,
}
}

View File

@ -5,6 +5,8 @@ import { generateApiRoute, generateSchemaFile } from '../utils/schematics'
import { capitalize, pluralize, singularize } from '../utils/formatting'
export function setupResourceRPC({ nuxt, rpc }: NuxtDevtoolsServerContext): any {
const runtimeConfig = nuxt.options.runtimeConfig as any
return {
// TODO: maybe separate functions
async generateResource(collection: Collection, resources: Resource[]) {
@ -13,9 +15,9 @@ export function setupResourceRPC({ nuxt, rpc }: NuxtDevtoolsServerContext): any
const dbName = capitalize(singular)
if (collection.fields) {
const schemaPath = resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`)
const schemaPath = resolve(nuxt.options.serverDir, runtimeConfig.mongoose.modelsDir, `${singular}.schema.ts`)
if (!fs.existsSync(schemaPath)) {
fs.ensureDirSync(resolve(nuxt.options.serverDir, 'utils/models'))
fs.ensureDirSync(resolve(nuxt.options.serverDir, runtimeConfig.mongoose.modelsDir))
fs.writeFileSync(schemaPath, generateSchemaFile(dbName, collection.fields))
}
@ -51,7 +53,7 @@ export function setupResourceRPC({ nuxt, rpc }: NuxtDevtoolsServerContext): any
async resourceSchema(collection: string) {
// TODO: use magicast
const singular = singularize(collection).toLowerCase()
const schemaPath = resolve(nuxt.options.serverDir, 'utils/models', `${singular}.schema.ts`)
const schemaPath = resolve(nuxt.options.serverDir, runtimeConfig.mongoose.modelsDir, `${singular}.schema.ts`)
if (fs.existsSync(schemaPath)) {
const content = fs.readFileSync(schemaPath, 'utf-8').match(/schema: \{(.|\n)*\}/g)
if (content) {

View File

@ -25,7 +25,7 @@ export interface ClientFunctions {
export interface Collection {
name: string
fields?: {}[]
fields?: object[]
}
export interface Resource {

View File

@ -11,5 +11,5 @@ export interface NuxtDevtoolsServerContext {
refresh: (event: keyof ServerFunctions) => void
extendServerRpc: <ClientFunctions = {}, ServerFunctions = {}>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>
extendServerRpc: <ClientFunctions = object, ServerFunctions = object>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>
}