小编Kar*_*mar的帖子

Go:如何使用枚举作为类型?

我有一个定义特定事件的事件列表(枚举):

package events

const (
    NEW_USER       = "NEW_USER"
    DIRECT_MESSAGE = "DIRECT_MESSAGE"
    DISCONNECT     = "DISCONNECT"
)
Run Code Online (Sandbox Code Playgroud)

并且有一个结构体将使用此枚举作为其属性之一

type ConnectionPayload struct {
    EventName    string      `json:"eventName"`
    EventPayload interface{} `json:"eventPayload"`
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以用作EventName而不是字符串的enum类型?

这是可能的,typescript不确定如何在 golang 中做到这一点。

我希望开发人员通过枚举强制使用正确的事件名称,而不是通过使用任何随机字符串作为 eventname 来犯错误

enums go

14
推荐指数
2
解决办法
2万
查看次数

React + NextJS - 受保护的路由

目标:如果登录用户尝试手动转到 /auth/signin,我想将其重定向到主页。

登录页面/组件:

const Signin = ({ currentUser }) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const { doRequest, errors } = useRequest({
        url: '/api/users/signin',
        method: 'post',
        body: {
            email, password
        },
        onSuccess: () => Router.push('/')
    });

    useEffect(() => {
        const loggedUser = () => {
            if (currentUser) {
                Router.push('/');
            }
        };
        loggedUser();
    }, []);

Run Code Online (Sandbox Code Playgroud)

自定义 _app 组件:

const AppComponent = ({ Component, pageProps, currentUser }) => {
    return (
        <div>
            <Header …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router server-side-rendering react-redux next.js

9
推荐指数
3
解决办法
2万
查看次数

React w/ Kubernetes 部署的 API 给出 ​​cors 错误

这与其他 cors 相关问题不同

我正在部署在 Digitalocean 上的 kubernetes 上的微服务上运行我的节点后端 api 。我已经阅读了与此问题相关的所有博客/论坛,但没有找到任何解决方案(特别是与 Digitalocean 相关的解决方案)。

我无法通过在“ localhost:3000 ”或 kubernetes 集群之外的任何地方运行的React 应用程序连接到集群。

它给我以下错误:

Access to XMLHttpRequest at 'http://cultor.dev/api/users/signin' 
from origin 'http://localhost:3000' has been blocked by 
CORS policy: Response to preflight request doesn't pass access 
control check: Redirect is not allowed for a preflight request.
Run Code Online (Sandbox Code Playgroud)

kubernetes 集群的负载均衡器正在监听“cultor.dev” ,它在/etc/hosts中设置为本地域。 我可以使用 Postman 让它工作!

注意: 我也尝试过使用 cors 包,但没有帮助。另外,如果我在我不想要的kubernetes 集群内运行这个 React 应用程序,它也可以正常工作。

Ingress nginx 配置(尝试使用官方网站上提到的注释):

Access to XMLHttpRequest at 'http://cultor.dev/api/users/signin' 
from origin …
Run Code Online (Sandbox Code Playgroud)

node.js reactjs digital-ocean kubernetes microservices

8
推荐指数
2
解决办法
1万
查看次数

React 测试库 - 检查按钮禁用属性

好的,我有一个需要at-least10 个字符的输入字段,它启用了显示 的按钮Save & Next

\n

如果description.length < 10,则它保持禁用状态。这在用户界面中运行良好。\n但我无法为其编写测试。

\n
test(\' Disables the save and next button if description < 10\', () => {\n    render(<StepOne />, { initialState });\n    const input = screen.getByLabelText(/description/i);\n    fireEvent.change(input, { target: { value: \'123456\' } }); //  Length < 10\n    const button = screen.getByText(\'Save & Next\');\n    console.log(button.innerHTML);\n    expect(button).toBeDisabled(true);\n  });\n
Run Code Online (Sandbox Code Playgroud)\n

错误:

\n
expect(element).toBeDisabled()\n\n    \xe2\x9d\x8c Received element is not disabled:\n      <span class="MuiButton-label" />\n
Run Code Online (Sandbox Code Playgroud)\n

我想知道我在这里缺少什么

\n

unit-testing reactjs react-testing-library react-hooks

7
推荐指数
1
解决办法
6433
查看次数

Go:如何在变量中使用上下文值?

我正在使用上下文在我的 Go Rest 应用程序的中间件中附加用户有效负载(特别是 userId)

// middleware
    // attaching payload to the request context
        claimsWithPayload, _ := token.Claims.(*handlers.Claims)
        ctx := context.WithValue(r.Context(), "userid", claimsWithPayload.Id)
        req := r.WithContext(ctx)
        h := http.HandlerFunc(handler)
        h.ServeHTTP(w, req)
Run Code Online (Sandbox Code Playgroud)

稍后在 http 处理程序中,我需要提取该用户 ID,string/integer 因为 context().Value() 返回一个接口{}

// handler 
a := r.Context().Value("userid") // THIS returns an interface{}
response := []byte("Your user ID is" + a) //  how do I use it as a string/integer??
w.Write(response)
Run Code Online (Sandbox Code Playgroud)

go

6
推荐指数
1
解决办法
9114
查看次数

Kubernetes - 如何在 PVC 中提及 hostPath?

我需要使用 PVC 来指定 PV 的规格,并且还需要确保它在 PV 中使用自定义本地存储路径。

我不知道如何在 PVC 中提及主机路径

这是 PVC 配置:

apiVersion: v1 
kind: PersistentVolumeClaim
metadata: 
  name: mongo-pvc 
spec: 
  accessModes: 
    - ReadWriteOnce
  resources: 
    requests: 
      storage: 1Gi
Run Code Online (Sandbox Code Playgroud)

这是 mongodb 部署:

spec:
    replicas: 1
    selector:
        matchLabels:
            app: mongo
    template:
        metadata:
            labels: 
                app: mongo
        spec:
            volumes: 
                - name: mongo-volume 
                  persistentVolumeClaim: 
                    claimName: mongo-pvc 
            containers:
                - name: mongo
                  image: mongo
                  ports:
                    - containerPort: 27017
                  volumeMounts: 
                    - name: mongo-volume 
                      mountPath: /data/db 
Run Code Online (Sandbox Code Playgroud)

我如何以及在哪里提及要在此处挂载的主机路径?

kubernetes microservices google-kubernetes-engine

5
推荐指数
2
解决办法
4493
查看次数

每次生产 Kafka 消息时都需要连接吗?

我创建了这个类,以使代码在发送/生成 Kafka 消息时更加可重用和干净。

我正在使用Node 和 Kafka 使用 KafkaJS

对此很陌生,我无法在互联网上的任何地方找到在生产应用程序中使用它的完美/好方法。

问题(简而言之):每次生成新消息时,我们是否需要作为生产者进行连接?我们不能像Redis 或 NATS一样保持连接吗?

这是我到目前为止所尝试过的:

使用案例

假设每次创建新用户时我都需要发送一条消息。

1.创建afka客户端

创建了kafka客户端,这样我们就不必每次都重新配置它

import { Kafka } from 'kafkajs';

class KafkaClient {
  private _client: Kafka;

  get client() {
    if (!this._client) {
      throw new Error('Cannot access client before initializing it');
    } else {
      return this._client;
    }
  }
  connect(clientId: string, brokers: string[]) {
    this._client = new Kafka({
      clientId,
      brokers,
    });
  }
}

export const producerClient = new KafkaClient();
Run Code Online (Sandbox Code Playgroud)

2.创建抽象发布者类

为所有类型的生产者创建了kafka生产者抽象类

import …
Run Code Online (Sandbox Code Playgroud)

javascript node.js apache-kafka typescript microservices

5
推荐指数
1
解决办法
2606
查看次数

strconv.Itoa 不接受 int64 类型的值

我正在学习使用 Go 创建 REST API。这就是我被困住的地方。

当用户发送 CREATE 请求时:

  1. 从文章片段中,我需要取出最后一篇文章
  2. 将ID(原始字符串)转换为整数
  3. 增加整数并将其转换回字符串并保存

文章结构

type Article struct {
    Id       string  `json:"id"`
    Title    string  `json:"title"`
    Desc     string  `json:"desc"`
    Content  string  `json:"content"`
}
Run Code Online (Sandbox Code Playgroud)

这是逻辑

// get the last id and convert it to integer and increment
    lastId, err := strconv.ParseInt(Articles[len(Articles) - 1].Id, 10, 64)
    lastId = lastId + 1 
    if err != nil {
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
    }
    response := []Article{
        {
            Id: strconv.Itoa(lastId),//  ERROR
            Title:   articleBody.Title,
            Desc:    articleBody.Desc,
            Content: articleBody.Content,
        }, …
Run Code Online (Sandbox Code Playgroud)

go

5
推荐指数
1
解决办法
9313
查看次数

反应 | JavaScript:需要比较两个对象

客观的:

我需要检查表单是否已被用户编辑。如果是,那么我将调用axios.put()函数。

问题:

由于在 JS 中, obj1 = { name: "John "} !== obj2 = { name: "John" } 我正在寻找一种更好的方法来比较两个对象。

我的方式(似乎效率低下):

const intialAddress= {
   city: "CA"
   line1: "testline1"
   line2: "testline2"
   phone: "7772815615"
   pin: "1234"
   state: "CA"
}

const [address, setAddress] = useState(initialAddress);
let addressFinalValue = {};
const addressValue = (e) => {
        addressFinalValue[e.target.name] = e.target.value;
    };

/***************************
 * The way I am doing it 
 **************************/

const submitHandler = (e) => {
  e.preventDefault();
  setAddress(addressFinalValue);
  if ( address.line1 !== initialAddress.line1 …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-redux

3
推荐指数
2
解决办法
2万
查看次数

Postgres jsonb 查询动态值

在 users 表中,我有一个 jsob 列experience,其 json 结构如下:

[
    {
        "field": "devops",
        "years": 9
    },
    {
        "field": "backend dev",
        "years": 7
    } 
... // could be N number of objects with different values
]
Run Code Online (Sandbox Code Playgroud)

业务需求

客户可以要求在任何领域有经验的人员以及在每个领域各自有多年的经验

这是一个示例查询

SELECT * FROM users
WHERE
jsonb_path_exists(experience, '$[*] ? (@.field == "devops" && @.years > 5)') and
jsonb_path_exists(experience, '$[*] ? (@.field == "backend dev" && @.years > 5)')
LIMIT 3;
Run Code Online (Sandbox Code Playgroud)

问题

假设我收到请求

[
  { field: "devops", years: 5 }, 
  { field: "java", years: …
Run Code Online (Sandbox Code Playgroud)

sql postgresql node.js sequelize.js typeorm

3
推荐指数
1
解决办法
2050
查看次数