title: How to prevent duplicate id in creating objects from SPA? Or should I stay with the db?
body: <p>I have a react app that fetches data from golang api which queries data from postgres database. One of my models is deeply nested JSON so I used JSONB datatype in postgres.</p>
  
  <pre><code>CREATE table rules (
      id serial primary key,
      rule jsonb
  );
  </code></pre>
  
  <p>In golang, I have the structure</p>
  
  <pre><code>type Rule struct {
      ID int `json:"id"`
      Name string `json:"name"`
      ...succeeding fields are deeply nested data
  }
  </code></pre>
  
  <p>And in the SPA I have the model</p>
  
  <pre><code>interface Rule {
      id number
      name string
      ....same as from the golang api model
  }
  </code></pre>
  
  <p>To create a new <code>Rule</code> object in the SPA, I assign <code>0</code> to <code>id</code>. The newly created rule is sent to golang rest api. Then in the api, I first ask the postgres database for the next value for the serial id (using POSTGRES <code>nextval</code>), assign that acquired id into the Rule struct ID field,</p>
  
  <pre><code>nextValidId := &lt;result of nextval&gt;
  rule.ID = nextValidId
  </code></pre>
  
  <p>JSON marshal the rule object then insert to db</p>
  
  <pre><code>ruleBytes, _ := json.Marshal(rule)
  INSERT INTO rules_table VALUES (&lt;nextValidId&gt;, &lt;ruleBytes&gt;);
  </code></pre>
  
  <p>This way I avoided duplicate ids which may happen if an SPA is handling the Id generation. However, I find my method somewhat complicated already. I know I can generate ids from SPA too but how do I avoid duplicated ids without using the method I used above? or am I overthinking things? </p>
  
  <p>Update1:
  I also thought about adding another Rule struct in golang without the <code>ID</code> field so that I don't have to use <code>nextval</code> just to put the id inside the JSON, but is it a good programming design to have multiple models for inserting and retrieving from db and another model for response to the SPA?</p>