如何在 FeathersJS 5 中创建服务的自定义路径

问题描述 投票:0回答:1

我在我的 Feathers 应用程序中创建了服务工作。我可以在 /jobs 端点上进行 CRUD。但现在我需要为该服务创建新的端点 /jobs-count。

我尝试了下面的代码,但它没有按预期工作。当我在没有身份验证的情况下使用它时,我可以获得响应,但是当我向其中添加身份验证(“jwt”)时,它仍然在加载。

jobs.js

// For more information about this file see https://dove.feathersjs.com/guides/cli/service.html
import { authenticate } from '@feathersjs/authentication'

import { hooks as schemaHooks } from '@feathersjs/schema'
import {
  jobsDataValidator,
  jobsPatchValidator,
  jobsQueryValidator,
  jobsResolver,
  jobsExternalResolver,
  jobsDataResolver,
  jobsPatchResolver,
  jobsQueryResolver
} from './jobs.schema.js'
import { JobsService, getOptions } from './jobs.class.js'
import { jobsPath, jobsMethods } from './jobs.shared.js'

export * from './jobs.class.js'
export * from './jobs.schema.js'

// A configure function that registers the service and its hooks via `app.configure`
export const jobs = (app) => {
  // Register our service on the Feathers application
  app.use(jobsPath, new JobsService(getOptions(app)), {
    // A list of all methods this service exposes externally
    methods: jobsMethods,
    // You can add additional custom events to be sent to clients here
    events: []
  })
  // Initialize hooks
  app.service(jobsPath).hooks({
    around: {
      all: [
        authenticate('jwt'),
        schemaHooks.resolveExternal(jobsExternalResolver),
        schemaHooks.resolveResult(jobsResolver)
      ]
    },
    before: {
      all: [schemaHooks.validateQuery(jobsQueryValidator), schemaHooks.resolveQuery(jobsQueryResolver)],
      find: [],
      get: [],
      create: [schemaHooks.validateData(jobsDataValidator), schemaHooks.resolveData(jobsDataResolver)],
      patch: [schemaHooks.validateData(jobsPatchValidator), schemaHooks.resolveData(jobsPatchResolver)],
      remove: []
    },
    after: {
      all: []
    },
    error: {
      all: []
    }
  })


  app.get('/getJobsCount', authentication("jwt") async (req, res) => {
    try {
      const jobsService = new JobsService(getOptions(app))
      const count = await jobsService.getJobsCount()
      res.status(200).json(count)
    } catch (error) {
      res.status(500).json({ error: 'Server error' })
    }
  })
}

这是我在 jobs.class.js 中的函数

async getJobsCount() {
    try {
      const jobsCount = await this.Model.count('id as count').from('jobs')
      return jobsCount[0].count
    } catch (error) {
      console.error('Error fetching office count:', error)
      throw new Error('Failed to fetch office count')
    }
  }

javascript authentication feathersjs
1个回答
0
投票

您有两个选择:

  1. 一般来说,Feathers 中的一条新路径是它自己的服务。您可以在
    jobs-count
    路径上创建自定义服务并仅实现
    find
    方法(使用
    this.options.app.service('jobs').Model
    而不是
    this.Model
  2. 您可以注册
    getJobsCount
    作为自定义服务方法
© www.soinside.com 2019 - 2024. All rights reserved.