Lesson 2 of 9 · 2 min 40 sec

Shop: Add a Module That Owns Its Data

Chapters

  1. Say what the module saves
  2. Give the module its methods
  3. Make it part of the app
  4. Call it and check it
Transcript
Download transcript

Say what the module saves

The Shop needs a tax rate. An admin sets it and checkout will read it. That is one saved number, and it gets a module of its own called Settings. The first file is memory, v one. Data lists what the module saves, here a single tax field that only Settings code can see. The memory attribute names the owner. Other modules will refer to Memory, and never to the fields. Beside it, the selector says which version the service uses today. The module also gets a constructor. It creates fresh Settings data with a tax of zero and returns it as a ticket for the parent to attach.

Give the module its methods

The service is declared in mod dot r s. The service attribute connects it to the current memory version. Tax is a read method. Set tax needs a write scope. It refuses a rate above ten thousand before it touches the data, and only then writes.

Make it part of the app

The root has a memory file too. It saves no fields of its own. It lists the modules attached to it, one slot each. The settings slot names Settings memory, version one, exactly. Install runs once, when the canister is first installed. It creates the root, calls each module's constructor, and attaches the result to its slot. Creating and attaching happen in the same scope. A ticket that is never attached is discarded when the scope ends. Data alone is not callable. Bind looks up the settings slot and builds the Settings service from it. The App keeps that service in a field marked service, which gives endpoints the call app dot settings. The root attribute names two startup callbacks. Init runs on first install and ends by binding the services. Restore runs after an upgrade. It opens the saved data and binds the services again. Services are rebuilt every time the program starts. Only the data is kept.

Call it and check it

Two endpoints finish the feature. Set tax is an update that only a controller may call. Tax is a query for anyone. Setting five hundred returns true, and the saved tax is five hundred. The Shop test checks both paths. It sets the tax, drops the app, opens it again, and reads five hundred. A second test confirms that ten thousand and one is refused and ten thousand is accepted.