public serverToClientPatch()

in uui-db/src/tempIds.tsx [128:179]


    public serverToClientPatch(patch: DbPatch<TTables>) {
        patch = this.copyPatch(patch);

        // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
        this.mapFields(
            patch,
            (f) => f.isGenerated,
            (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
                let clientId = this.getServerToClientMap(tableName).get(fieldValue);
                if (!clientId) {
                    clientId = getTempId();
                    this.clientToServerIds.set(clientId, fieldValue);
                    this.getServerToClientMap(tableName).set(fieldValue, clientId);
                }
                entityPatch[fieldName] = clientId;
            },
        );

        this.mapFields(
            patch,
            (f) => !!(f.fk || f.default != null || f.toClient),
            (fieldName, fieldSchema, fieldValue, entityPatch) => {
                let isUndefined = typeof fieldValue === 'undefined';

                if (fieldSchema.default != null && fieldValue == null) {
                    fieldValue = fieldSchema.default;
                    isUndefined = false;
                }

                if (fieldSchema.fk && fieldValue != null) {
                    const fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
                    let clientId = this.getServerToClientMap(fkTableName as keyof TTables).get(fieldValue);
                    if (!clientId) {
                        clientId = getTempId();
                        this.clientToServerIds.set(clientId, fieldValue);
                        this.getServerToClientMap(fkTableName as keyof TTables).set(fieldValue, clientId);
                    }
                    fieldValue = clientId;
                }

                if (!isUndefined && fieldSchema.toClient) {
                    fieldValue = fieldSchema.toClient(fieldValue);
                }

                if (!isUndefined) {
                    entityPatch[fieldName] = fieldValue;
                }
            },
        );

        return patch;
    }