PageSourceSearch

https://docs.ignite.com/assets/js/ad2dcfb8.0959e6ff.js

js ignite.com collected 2026-10-03 23:19:00 UTC 10,755 bytes, 1 lines download raw bytes

1"use strict";(globalThis.webpackChunkmy_website=globalThis.webpackChunkmy_website||[]).push([[3027],{15680(e,t,n){n.d(t,{xA:()=>d,yg:()=>c});var o=n(96540);function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e,t){if(null==e)return{};var n,o,s=function(e,t){if(null==e)return{};var n,o,s={},r=Object.keys(e);for(o=0;o<r.length;o++)n=r[o],t.indexOf(n)>=0||(s[n]=e[n]);return s}(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(o=0;o<r.length;o++)n=r[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}var p=o.createContext({}),l=function(e){var t=o.useContext(p),n=t;return e&&(n="function"==typeof e?e(t):a(a({},t),e)),n},d=function(e){var t=l(e.components);return o.createElement(p.Provider,{value:t},e.children)},g={inlineCode:"code",wrapper:function(e){var t=e.children;return o.createElement(o.Fragment,{},t)}},u=o.forwardRef((function(e,t){var n=e.components,s=e.mdxType,r=e.originalType,p=e.parentName,d=i(e,["components","mdxType","originalType","parentName"]),u=l(n),c=s,m=u["".concat(p,".").concat(c)]||u[c]||g[c]||r;return n?o.createElement(m,a(a({ref:t},d),{},{components:n})):o.createElement(m,a({ref:t},d))}));function c(e,t){var n=arguments,s=t&&t.mdxType;if("string"==typeof e||s){var r=n.length,a=new Array(r);a[0]=u;var i={};for(var p in t)hasOwnProperty.call(t,p)&&(i[p]=t[p]);i.originalType=e,i.mdxType="string"==typeof e?e:s,a[1]=i;for(var l=2;l<r;l++)a[l]=n[l];return o.createElement.apply(null,a)}return o.createElement.apply(null,n)}u.displayName="MDXCreateElement"},23170(e,t,n){n.r(t),n.d(t,{assets:()=>p,contentTitle:()=>a,default:()=>g,frontMatter:()=>r,metadata:()=>i,toc:()=>l});var o=n(58168),s=(n(96540),n(15680));const r={},a="Updating posts",i={unversionedId:"guide/blog/update",id:"version-v0.26/guide/blog/update",title:"Updating posts",description:'In this chapter, we will be focusing on the process of handling an "update post"',source:"@site/versioned_docs/version-v0.26/02-guide/04-blog/04-update.md",sourceDirName:"02-guide/04-blog",slug:"/guide/blog/update",permalink:"/v0.26/guide/blog/update",draft:!1,tags:[],version:"v0.26",sidebarPosition:4,frontMatter:{},sidebar:"tutorialSidebar",previous:{title:"Creating posts",permalink:"/v0.26/guide/blog/create"},next:{title:"Deleting posts",permalink:"/v0.26/guide/blog/delete"}},p={},l=[{value:"Getting posts",id:"getting-posts",level:2},{value:"Setting posts",id:"setting-posts",level:2},{value:"Update posts",id:"update-posts",level:2},{value:"Summary",id:"summary",level:2}],d={toc:l};function g(e){let{components:t,...n}=e;return(0,s.yg)("wrapper",(0,o.A)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,s.yg)("h1",{id:"updating-posts"},"Updating posts"),(0,s.yg)("p",null,'In this chapter, we will be focusing on the process of handling an "update post"\nmessage.'),(0,s.yg)("p",null,'To update a post, you need to retrieve the specific post from the store using\nthe "Get" operation, modify the values, and then write the updated post back to\nthe store using the "Set" operation.'),(0,s.yg)("p",null,"Let's first implement a getter and a setter logic."),(0,s.yg)("h2",{id:"getting-posts"},"Getting posts"),(0,s.yg)("p",null,"Implement the ",(0,s.yg)("inlineCode",{parentName:"p"},"GetPost")," keeper method in ",(0,s.yg)("inlineCode",{parentName:"p"},"post.go"),":"),(0,s.yg)("pre",null,(0,s.yg)("code",{parentName:"pre",className:"language-go",metastring:'title="x/blog/keeper/post.go"',title:'"x/blog/keeper/post.go"'},"func (k Keeper) GetPost(ctx sdk.Context, id uint64) (val types.Post, found bool) {\n    store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.PostKey))\n    b := store.Get(GetPostIDBytes(id))\n    if b == nil {\n        return val, false\n    }\n    k.cdc.MustUnmarshal(b, &val)\n    return val, true\n}\n")),(0,s.yg)("p",null,(0,s.yg)("inlineCode",{parentName:"p"},"GetPost")," takes in two arguments: a context ",(0,s.yg)("inlineCode",{parentName:"p"},"ctx")," and an ",(0,s.yg)("inlineCode",{parentName:"p"},"id")," of type ",(0,s.yg)("inlineCode",{parentName:"p"},"uint64"),"\nrepresenting the ID of the post to be retrieved. It returns a ",(0,s.yg)("inlineCode",{parentName:"p"},"types.Post"),"\nstruct containing the values of the post, and a boolean value indicating whether\nthe post was found in the database."),(0,s.yg)("p",null,"The function first creates a ",(0,s.yg)("inlineCode",{parentName:"p"},"store")," using the ",(0,s.yg)("inlineCode",{parentName:"p"},"prefix.NewStore")," method, passing\nin the key-value store from the context and the ",(0,s.yg)("inlineCode",{parentName:"p"},"types.KeyPrefix")," function\napplied to the ",(0,s.yg)("inlineCode",{parentName:"p"},"types.PostKey")," constant as arguments. It then attempts to\nretrieve the post from the store using the ",(0,s.yg)("inlineCode",{parentName:"p"},"store.Get")," method, passing in the ID\nof the post as a byte slice. If the post is not found in the store, it returns\nan empty ",(0,s.yg)("inlineCode",{parentName:"p"},"types.Post")," struct and a boolean value of false."),(0,s.yg)("p",null,"If the post is found in the store, the function unmarshals the retrieved byte\nslice into a ",(0,s.yg)("inlineCode",{parentName:"p"},"types.Post")," struct using the ",(0,s.yg)("inlineCode",{parentName:"p"},"cdc.MustUnmarshal")," method, passing\nin a pointer to the val variable as an argument. It then returns the val struct\nand a boolean value of true to indicate that the post was found in the database."),(0,s.yg)("h2",{id:"setting-posts"},"Setting posts"),(0,s.yg)("p",null,"Implement the ",(0,s.yg)("inlineCode",{parentName:"p"},"SetPost")," keeper method in ",(0,s.yg)("inlineCode",{parentName:"p"},"post.go"),":"),(0,s.yg)("pre",null,(0,s.yg)("code",{parentName:"pre",className:"language-go",metastring:'title="x/blog/keeper/post.go"',title:'"x/blog/keeper/post.go"'},"func (k Keeper) SetPost(ctx sdk.Context, post types.Post) {\n    store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.PostKey))\n    b := k.cdc.MustMarshal(&post)\n    store.Set(GetPostIDBytes(post.Id), b)\n}\n")),(0,s.yg)("p",null,(0,s.yg)("inlineCode",{parentName:"p"},"SetPost")," takes in two arguments: a context ",(0,s.yg)("inlineCode",{parentName:"p"},"ctx")," and a ",(0,s.yg)("inlineCode",{parentName:"p"},"types.Post")," struct\ncontaining the updated values for the post. The function does not return\nanything."),(0,s.yg)("p",null,"The function first creates a store using the ",(0,s.yg)("inlineCode",{parentName:"p"},"prefix.NewStore")," method, passing\nin the key-value store from the context and the ",(0,s.yg)("inlineCode",{parentName:"p"},"types.KeyPrefix")," function\napplied to the ",(0,s.yg)("inlineCode",{parentName:"p"},"types.PostKey")," constant as arguments. It then marshals the\nupdated post struct into a byte slice using the ",(0,s.yg)("inlineCode",{parentName:"p"},"cdc.MustMarshal")," method,\npassing in a pointer to the post struct as an argument. Finally, it updates the\npost in the store using the ",(0,s.yg)("inlineCode",{parentName:"p"},"store.Set")," method, passing in the ID of the post as\na byte slice and the marshaled post struct as arguments."),(0,s.yg)("h2",{id:"update-posts"},"Update posts"),(0,s.yg)("pre",null,(0,s.yg)("code",{parentName:"pre",className:"language-go",metastring:'title="x/blog/keeper/msg_server_update_post.go"',title:'"x/blog/keeper/msg_server_update_post.go"'},'package keeper\n\nimport (\n    "context"\n    "fmt"\n\n    "blog/x/blog/types"\n\n    sdk "github.com/cosmos/cosmos-sdk/types"\n    sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"\n)\n\nfunc (k msgServer) UpdatePost(goCtx context.Context, msg *types.MsgUpdatePost) (*types.MsgUpdatePostResponse, error) {\n    ctx := s
1dk.UnwrapSDKContext(goCtx)\n    var post = types.Post{\n        Creator: msg.Creator,\n        Id:      msg.Id,\n        Title:   msg.Title,\n        Body:    msg.Body,\n    }\n    val, found := k.GetPost(ctx, msg.Id)\n    if !found {\n        return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn\'t exist", msg.Id))\n    }\n    if msg.Creator != val.Creator {\n        return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner")\n    }\n    k.SetPost(ctx, post)\n    return &types.MsgUpdatePostResponse{}, nil\n}\n')),(0,s.yg)("p",null,(0,s.yg)("inlineCode",{parentName:"p"},"UpdatePost")," takes in a context and a message ",(0,s.yg)("inlineCode",{parentName:"p"},"MsgUpdatePost")," as input, and\nreturns a response ",(0,s.yg)("inlineCode",{parentName:"p"},"MsgUpdatePostResponse")," and an ",(0,s.yg)("inlineCode",{parentName:"p"},"error"),". The function first\nretrieves the current values of the post from the database using the provided\n",(0,s.yg)("inlineCode",{parentName:"p"},"msg.Id"),", and checks if the post exists and if the ",(0,s.yg)("inlineCode",{parentName:"p"},"msg.Creator")," is the same as\nthe current owner of the post. If either of these checks fail, it returns an\nerror. If both checks pass, it updates the post in the database with the new\nvalues provided in ",(0,s.yg)("inlineCode",{parentName:"p"},"msg"),", and returns a response without an error."),(0,s.yg)("h2",{id:"summary"},"Summary"),(0,s.yg)("p",null,"Well done! You have successfully implemented a number of important methods for\nmanaging posts within a store."),(0,s.yg)("p",null,"The ",(0,s.yg)("inlineCode",{parentName:"p"},"GetPost")," method allows you to retrieve a specific post from the store based\non its unique identification number, or post ID. This can be useful for\ndisplaying a specific post to a user, or for updating it."),(0,s.yg)("p",null,"The ",(0,s.yg)("inlineCode",{parentName:"p"},"SetPost")," method enables you to update an existing post in the store. This\ncan be useful for correcting mistakes or updating the content of a post as new\ninformation becomes available."),(0,s.yg)("p",null,"Finally, you implemented the ",(0,s.yg)("inlineCode",{parentName:"p"},"UpdatePost")," method, which is called whenever the\nblockchain processes a message requesting an update to a post."))}g.isMDXComponent=!0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.